Browse Source

Move schemas to separate location, add docs & doc generation scripts, update autogenerated files

Leszek Wiesner 3 years ago
parent
commit
d887eb7bef
63 changed files with 3209 additions and 1185 deletions
  1. 24 405
      distributor-node/README.md
  2. 381 0
      distributor-node/docs/api/index.md
  3. 139 0
      distributor-node/docs/api/templates/main.dot
  4. 48 0
      distributor-node/docs/commands/dev.md
  5. 25 0
      distributor-node/docs/commands/help.md
  6. 367 0
      distributor-node/docs/commands/leader.md
  7. 70 0
      distributor-node/docs/commands/operator.md
  8. 25 0
      distributor-node/docs/commands/start.md
  9. 343 0
      distributor-node/docs/node/index.md
  10. 25 0
      distributor-node/docs/schema/README.md
  11. 7 0
      distributor-node/docs/schema/definition-properties-buckets-oneof-0-items.md
  12. 7 0
      distributor-node/docs/schema/definition-properties-buckets-oneof-0.md
  13. 11 0
      distributor-node/docs/schema/definition-properties-buckets-oneof-1.md
  14. 9 0
      distributor-node/docs/schema/definition-properties-buckets.md
  15. 3 0
      distributor-node/docs/schema/definition-properties-directories-assets.md
  16. 3 0
      distributor-node/docs/schema/definition-properties-directories-cachestate.md
  17. 3 0
      distributor-node/docs/schema/definition-properties-directories-logs.md
  18. 3 0
      distributor-node/docs/schema/definition-properties-directories-properties-cache.md
  19. 3 0
      distributor-node/docs/schema/definition-properties-directories-properties-data.md
  20. 3 0
      distributor-node/docs/schema/definition-properties-directories-properties-logs.md
  21. 3 0
      distributor-node/docs/schema/definition-properties-directories.md
  22. 3 0
      distributor-node/docs/schema/definition-properties-endpoints-properties-elasticsearch.md
  23. 3 0
      distributor-node/docs/schema/definition-properties-endpoints-properties-joystreamnodews.md
  24. 3 0
      distributor-node/docs/schema/definition-properties-endpoints-properties-querynode.md
  25. 3 0
      distributor-node/docs/schema/definition-properties-endpoints-properties-substratenode.md
  26. 65 0
      distributor-node/docs/schema/definition-properties-endpoints.md
  27. 3 0
      distributor-node/docs/schema/definition-properties-id.md
  28. 7 0
      distributor-node/docs/schema/definition-properties-intervals-properties-cachecleanup.md
  29. 7 0
      distributor-node/docs/schema/definition-properties-intervals-properties-checkstoragenoderesponsetimes.md
  30. 7 0
      distributor-node/docs/schema/definition-properties-intervals-properties-savecachestate.md
  31. 77 0
      distributor-node/docs/schema/definition-properties-intervals.md
  32. 3 0
      distributor-node/docs/schema/definition-properties-keys-items.md
  33. 7 0
      distributor-node/docs/schema/definition-properties-keys.md
  34. 7 0
      distributor-node/docs/schema/definition-properties-limits-properties-maxconcurrentoutboundconnections.md
  35. 7 0
      distributor-node/docs/schema/definition-properties-limits-properties-maxconcurrentstoragenodedownloads.md
  36. 7 0
      distributor-node/docs/schema/definition-properties-limits-properties-outboundrequeststimeout.md
  37. 13 0
      distributor-node/docs/schema/definition-properties-limits-properties-storage.md
  38. 106 0
      distributor-node/docs/schema/definition-properties-limits.md
  39. 18 0
      distributor-node/docs/schema/definition-properties-log-properties-console.md
  40. 18 0
      distributor-node/docs/schema/definition-properties-log-properties-elastic.md
  41. 18 0
      distributor-node/docs/schema/definition-properties-log-properties-file.md
  42. 110 0
      distributor-node/docs/schema/definition-properties-log.md
  43. 7 0
      distributor-node/docs/schema/definition-properties-port.md
  44. 7 0
      distributor-node/docs/schema/definition-properties-workerid.md
  45. 197 0
      distributor-node/docs/schema/definition.md
  46. 9 4
      distributor-node/package.json
  47. 2 2
      distributor-node/src/api-spec/openapi.yml
  48. 171 0
      distributor-node/src/schemas/configSchema.ts
  49. 0 0
      distributor-node/src/schemas/familyMetadataSchema.ts
  50. 3 3
      distributor-node/src/schemas/index.ts
  51. 0 0
      distributor-node/src/schemas/operatorMetadataSchema.ts
  52. 8 0
      distributor-node/src/schemas/scripts/generateConfigDoc.ts
  53. 1 1
      distributor-node/src/schemas/scripts/generateTypes.ts
  54. 2 2
      distributor-node/src/services/networking/NetworkingService.ts
  55. 30 16
      distributor-node/src/services/networking/distributor-node/generated/api.ts
  56. 175 641
      distributor-node/src/services/networking/query-node/generated/schema.ts
  57. 1 1
      distributor-node/src/services/parsers/ConfigParserService.ts
  58. 11 10
      distributor-node/src/services/server/controllers/public.ts
  59. 1 1
      distributor-node/src/services/validation/ValidationService.ts
  60. 0 61
      distributor-node/src/services/validation/schemas/configSchema.ts
  61. 0 10
      distributor-node/src/services/validation/schemas/utils.ts
  62. 72 8
      distributor-node/src/types/generated/ConfigJson.d.ts
  63. 518 20
      yarn.lock

+ 24 - 405
distributor-node/README.md

@@ -1,419 +1,38 @@
-@joystream/distributor-cli
-==========================
+# Joystream Distributor CLI
 
-Joystream distributor node CLI
+The Joystream Distributor CLI package contains a set of commands that allow:
+- running the actual distributor node,
+- performing the node operator on-chain duties (like setting the node metadata)
+- performing the distribution working group leader on-chain duties (like setting the distribution system limits, assigning distribution bags and buckets)
 
-[![oclif](https://img.shields.io/badge/cli-oclif-brightgreen.svg)](https://oclif.io)
-[![Version](https://img.shields.io/npm/v/@joystream/distributor-cli.svg)](https://npmjs.org/package/@joystream/distributor-cli)
-[![Downloads/week](https://img.shields.io/npm/dw/@joystream/distributor-cli.svg)](https://npmjs.org/package/@joystream/distributor-cli)
-[![License](https://img.shields.io/npm/l/@joystream/distributor-cli.svg)](https://github.com/Joystream/joystream/blob/master/package.json)
+**To see the list of all available commands and their flags / arguments, check out the [commands](docs/commands/index.md) documentation.**
 
-<!-- toc -->
-* [Usage](#usage)
-* [Commands](#commands)
-<!-- tocstop -->
-# Usage
-<!-- usage -->
-```sh-session
-$ npm install -g @joystream/distributor-cli
-$ joystream-distributor COMMAND
-running command...
-$ joystream-distributor (-v|--version|version)
-@joystream/distributor-cli/0.1.0 linux-x64 node-v14.17.3
-$ joystream-distributor --help [COMMAND]
-USAGE
-  $ joystream-distributor COMMAND
-...
-```
-<!-- usagestop -->
-# Commands
-<!-- commands -->
-* [`joystream-distributor dev:init`](#joystream-distributor-devinit)
-* [`joystream-distributor help [COMMAND]`](#joystream-distributor-help-command)
-* [`joystream-distributor leader:cancel-invitation`](#joystream-distributor-leadercancel-invitation)
-* [`joystream-distributor leader:create-bucket`](#joystream-distributor-leadercreate-bucket)
-* [`joystream-distributor leader:create-bucket-family`](#joystream-distributor-leadercreate-bucket-family)
-* [`joystream-distributor leader:delete-bucket`](#joystream-distributor-leaderdelete-bucket)
-* [`joystream-distributor leader:delete-bucket-family`](#joystream-distributor-leaderdelete-bucket-family)
-* [`joystream-distributor leader:invite-bucket-operator`](#joystream-distributor-leaderinvite-bucket-operator)
-* [`joystream-distributor leader:set-buckets-per-bag-limit`](#joystream-distributor-leaderset-buckets-per-bag-limit)
-* [`joystream-distributor leader:update-bag`](#joystream-distributor-leaderupdate-bag)
-* [`joystream-distributor leader:update-bucket-mode`](#joystream-distributor-leaderupdate-bucket-mode)
-* [`joystream-distributor leader:update-bucket-status`](#joystream-distributor-leaderupdate-bucket-status)
-* [`joystream-distributor leader:update-dynamic-bag-policy`](#joystream-distributor-leaderupdate-dynamic-bag-policy)
-* [`joystream-distributor operator:accept-invitation`](#joystream-distributor-operatoraccept-invitation)
-* [`joystream-distributor operator:set-metadata`](#joystream-distributor-operatorset-metadata)
-* [`joystream-distributor start`](#joystream-distributor-start)
+## Configuration
 
-## `joystream-distributor dev:init`
+### Config file
 
-Initialize development environment. Sets Alice as distributor working group leader.
+All the configuration values required by Joystream Distributor CLI are provided via a single configuration file (either `yml` or `json`).
 
-```
-USAGE
-  $ joystream-distributor dev:init
+The path to the configuration will be (ordered from highest to lowest priority):
+- The value of `--configPath` flag provided when running a command, _or_
+- The value of `CONFIG_PATH` environment variable, _or_
+- `config.yml` in the current working directory by default
 
-OPTIONS
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
+### ENV variables
 
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-```
+All configuration values can be overriden using environment variables, which may be useful when running the distributor node as docker service.
 
-_See code: [src/commands/dev/init.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/dev/init.ts)_
+To determine environment variable name based on a config key, for example `intervals.cacheCleanup`, use the following formula:
+- convert `pascalCase` fieldnames to `SCREAMING_SNAKE_CASE`: `intervals.cacheCleanup` => `INTERVALS.CACHE_CLEANUP`
+- replace all dots with `__`: `INTERVALS.CACHE_CLEANUP` => `INTERVALS__CACHE_CLEANUP`
+- add `JOYSTREAM_DISTRIBUTOR__` prefix: `INTERVALS__CACHE_CLEANUP` => `JOYSTREAM_DISTRIBUTOR__INTERVALS__CACHE_CLEANUP`
 
-## `joystream-distributor help [COMMAND]`
+In case of arrays, the values must be provided as json string, for example `JOYSTREAM_DISTRIBUTOR__KEYS="[\"//Bob\"]`.
 
-display help for joystream-distributor
+For more envirnoment variable examples see the `distributor-node` service configuration in [docker-compose.yml](../docker-compose.yml).
 
-```
-USAGE
-  $ joystream-distributor help [COMMAND]
+**For detailed configuration reference, checkout the [config schema](docs/schema/definition.md) documentation.**
 
-ARGUMENTS
-  COMMAND  command to show help for
+## Distributor Node
 
-OPTIONS
-  --all  see all commands in CLI
-```
-
-_See code: [@oclif/plugin-help](https://github.com/oclif/plugin-help/blob/v2.2.3/src/commands/help.ts)_
-
-## `joystream-distributor leader:cancel-invitation`
-
-Cancel pending distribution bucket operator invitation.
-
-```
-USAGE
-  $ joystream-distributor leader:cancel-invitation
-
-OPTIONS
-  -B, --bucketId=bucketId      (required) Distribution bucket id
-
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -f, --familyId=familyId      (required) Distribution bucket family id
-
-  -w, --workerId=workerId      (required) ID of the invited operator (distribution group worker)
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-
-DESCRIPTION
-  Requires distribution working group leader permissions.
-```
-
-_See code: [src/commands/leader/cancel-invitation.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/cancel-invitation.ts)_
-
-## `joystream-distributor leader:create-bucket`
-
-Create new distribution bucket. Requires distribution working group leader permissions.
-
-```
-USAGE
-  $ joystream-distributor leader:create-bucket
-
-OPTIONS
-  -a, --acceptingBags=(yes|no)  [default: no] Whether the created bucket should accept new bags
-
-  -c, --configPath=configPath   [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                                directory)
-
-  -f, --familyId=familyId       (required) Distribution bucket family id
-
-  -y, --yes                     Answer "yes" to any prompt, skipping any manual confirmations
-```
-
-_See code: [src/commands/leader/create-bucket.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/create-bucket.ts)_
-
-## `joystream-distributor leader:create-bucket-family`
-
-Create new distribution bucket family. Requires distribution working group leader permissions.
-
-```
-USAGE
-  $ joystream-distributor leader:create-bucket-family
-
-OPTIONS
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-```
-
-_See code: [src/commands/leader/create-bucket-family.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/create-bucket-family.ts)_
-
-## `joystream-distributor leader:delete-bucket`
-
-Delete distribution bucket. The bucket must have no operators. Requires distribution working group leader permissions.
-
-```
-USAGE
-  $ joystream-distributor leader:delete-bucket
-
-OPTIONS
-  -B, --bucketId=bucketId      (required) Distribution bucket id
-
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -f, --familyId=familyId      (required) Distribution bucket family id
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-```
-
-_See code: [src/commands/leader/delete-bucket.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/delete-bucket.ts)_
-
-## `joystream-distributor leader:delete-bucket-family`
-
-Delete distribution bucket family. Requires distribution working group leader permissions.
-
-```
-USAGE
-  $ joystream-distributor leader:delete-bucket-family
-
-OPTIONS
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -f, --familyId=familyId      (required) Distribution bucket family id
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-```
-
-_See code: [src/commands/leader/delete-bucket-family.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/delete-bucket-family.ts)_
-
-## `joystream-distributor leader:invite-bucket-operator`
-
-Invite distribution bucket operator (distribution group worker).
-
-```
-USAGE
-  $ joystream-distributor leader:invite-bucket-operator
-
-OPTIONS
-  -B, --bucketId=bucketId      (required) Distribution bucket id
-
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -f, --familyId=familyId      (required) Distribution bucket family id
-
-  -w, --workerId=workerId      (required) ID of the distribution group worker to invite as bucket operator
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-
-DESCRIPTION
-  The specified bucket must not have any operator currently.
-     Requires distribution working group leader permissions.
-```
-
-_See code: [src/commands/leader/invite-bucket-operator.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/invite-bucket-operator.ts)_
-
-## `joystream-distributor leader:set-buckets-per-bag-limit`
-
-Set max. distribution buckets per bag limit. Requires distribution working group leader permissions.
-
-```
-USAGE
-  $ joystream-distributor leader:set-buckets-per-bag-limit
-
-OPTIONS
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -l, --limit=limit            (required) New limit value
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-```
-
-_See code: [src/commands/leader/set-buckets-per-bag-limit.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/set-buckets-per-bag-limit.ts)_
-
-## `joystream-distributor leader:update-bag`
-
-Add/remove distribution buckets from a bag.
-
-```
-USAGE
-  $ joystream-distributor leader:update-bag
-
-OPTIONS
-  -a, --add=add
-      [default: ] ID of a bucket to add to bag
-
-  -b, --bagId=bagId
-      (required) Bag ID. Format: {bag_type}:{sub_type}:{id}.
-           - Bag types: 'static', 'dynamic'
-           - Sub types: 'static:council', 'static:wg', 'dynamic:member', 'dynamic:channel'
-           - Id:
-             - absent for 'static:council'
-             - working group name for 'static:wg'
-             - integer for 'dynamic:member' and 'dynamic:channel'
-           Examples:
-           - static:council
-           - static:wg:storage
-           - dynamic:member:4
-
-  -c, --configPath=configPath
-      [default: ./config.yml] Path to config JSON/YAML file (relative to current working directory)
-
-  -f, --familyId=familyId
-      (required) ID of the distribution bucket family
-
-  -r, --remove=remove
-      [default: ] ID of a bucket to remove from bag
-
-  -y, --yes
-      Answer "yes" to any prompt, skipping any manual confirmations
-
-EXAMPLE
-  $ joystream-distributor leader:update-bag -b 1 -f 1 -a 1 -a 2 -a 3 -r 4 -r 5
-```
-
-_See code: [src/commands/leader/update-bag.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/update-bag.ts)_
-
-## `joystream-distributor leader:update-bucket-mode`
-
-Update distribution bucket mode ("distributing" flag). Requires distribution working group leader permissions.
-
-```
-USAGE
-  $ joystream-distributor leader:update-bucket-mode
-
-OPTIONS
-  -B, --bucketId=bucketId      (required) Distribution bucket id
-
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -d, --mode=(on|off)          (required) Whether the bucket should be "on" (distributing) or "off" (not distributing)
-
-  -f, --familyId=familyId      (required) Distribution bucket family id
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-```
-
-_See code: [src/commands/leader/update-bucket-mode.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/update-bucket-mode.ts)_
-
-## `joystream-distributor leader:update-bucket-status`
-
-Update distribution bucket status ("acceptingNewBags" flag). Requires distribution working group leader permissions.
-
-```
-USAGE
-  $ joystream-distributor leader:update-bucket-status
-
-OPTIONS
-  -B, --bucketId=bucketId       (required) Distribution bucket id
-  -a, --acceptingBags=(yes|no)  (required) Whether the bucket should accept new bags
-
-  -c, --configPath=configPath   [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                                directory)
-
-  -f, --familyId=familyId       (required) Distribution bucket family id
-
-  -y, --yes                     Answer "yes" to any prompt, skipping any manual confirmations
-```
-
-_See code: [src/commands/leader/update-bucket-status.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/update-bucket-status.ts)_
-
-## `joystream-distributor leader:update-dynamic-bag-policy`
-
-Update dynamic bag creation policy (number of buckets by family that should store given dynamic bag type).
-
-```
-USAGE
-  $ joystream-distributor leader:update-dynamic-bag-policy
-
-OPTIONS
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -p, --policy=policy          Key-value pair of {familyId}:{numberOfBuckets}
-
-  -t, --type=(Member|Channel)  (required) Dynamic bag type
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-
-DESCRIPTION
-  Requires distribution working group leader permissions.
-
-EXAMPLE
-  $ joystream-distributor leader:update-dynamic-bag-policy -t Member -p 1:5 -p 2:10 -p 3:5
-```
-
-_See code: [src/commands/leader/update-dynamic-bag-policy.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/update-dynamic-bag-policy.ts)_
-
-## `joystream-distributor operator:accept-invitation`
-
-Accept pending distribution bucket operator invitation.
-
-```
-USAGE
-  $ joystream-distributor operator:accept-invitation
-
-OPTIONS
-  -B, --bucketId=bucketId      (required) Distribution bucket id
-
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -f, --familyId=familyId      (required) Distribution bucket family id
-
-  -w, --workerId=workerId      (required) ID of the invited operator (distribution group worker)
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-
-DESCRIPTION
-  Requires the invited distribution group worker role key.
-```
-
-_See code: [src/commands/operator/accept-invitation.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/operator/accept-invitation.ts)_
-
-## `joystream-distributor operator:set-metadata`
-
-Set/update distribution bucket operator metadata.
-
-```
-USAGE
-  $ joystream-distributor operator:set-metadata
-
-OPTIONS
-  -B, --bucketId=bucketId      (required) Distribution bucket id
-
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -e, --endpoint=endpoint      Root distribution node endpoint
-
-  -f, --familyId=familyId      (required) Distribution bucket family id
-
-  -i, --input=input            Path to JSON metadata file
-
-  -w, --workerId=workerId      (required) ID of the invited operator (distribution group worker)
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-
-DESCRIPTION
-  Requires active distribution bucket operator worker role key.
-```
-
-_See code: [src/commands/operator/set-metadata.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/operator/set-metadata.ts)_
-
-## `joystream-distributor start`
-
-Start the node
-
-```
-USAGE
-  $ joystream-distributor start
-
-OPTIONS
-  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
-                               directory)
-
-  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
-```
-
-_See code: [src/commands/start.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/start.ts)_
-<!-- commandsstop -->
+**To understand how the distributor node works in detail, checkout the [node](docs/node/index.md) documentation.**

+ 381 - 0
distributor-node/docs/api/index.md

@@ -0,0 +1,381 @@
+---
+title: Distributor node API v0.1.0
+language_tabs:
+  - javascript: JavaScript
+  - shell: Shell
+language_clients:
+  - javascript: ""
+  - shell: ""
+toc_footers:
+  - <a href="https://github.com/Joystream/joystream/issues/2224">Distributor
+    node API</a>
+includes: []
+search: true
+highlight_theme: darkula
+headingLevel: 2
+
+---
+
+<h1 id="distributor-node-api">Distributor node API v0.1.0</h1>
+
+> Scroll down for code samples, example requests and responses.
+
+Distributor node API
+
+Base URLs:
+
+* <a href="http://localhost:3334/api/v1/">http://localhost:3334/api/v1/</a>
+
+Email: <a href="mailto:info@joystream.org">Support</a> 
+License: <a href="https://spdx.org/licenses/GPL-3.0-only.html">GPL-3.0-only</a>
+
+<h1 id="distributor-node-api-public">public</h1>
+
+Public distributor node API
+
+## public.status
+
+<a id="opIdpublic.status"></a>
+
+> Code samples
+
+```javascript
+
+const headers = {
+  'Accept':'application/json'
+};
+
+fetch('http://localhost:3334/api/v1/status',
+{
+  method: 'GET',
+
+  headers: headers
+})
+.then(function(res) {
+    return res.json();
+}).then(function(body) {
+    console.log(body);
+});
+
+```
+
+```shell
+# You can also use wget
+curl -X GET http://localhost:3334/api/v1/status \
+  -H 'Accept: application/json'
+
+```
+
+`GET /status`
+
+Returns json object describing current node status.
+
+> Example responses
+
+> 200 Response
+
+```json
+{
+  "id": "string",
+  "objectsInCache": 0,
+  "storageLimit": 0,
+  "storageUsed": 0,
+  "uptime": 0,
+  "downloadsInProgress": 0
+}
+```
+
+<h3 id="public.status-responses">Responses</h3>
+
+|Status|Meaning|Description|Schema|
+|---|---|---|---|
+|200|[OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)|OK|[StatusResponse](#schemastatusresponse)|
+|500|[Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)|Unexpected server error|None|
+
+<aside class="success">
+This operation does not require authentication
+</aside>
+
+## public.buckets
+
+<a id="opIdpublic.buckets"></a>
+
+> Code samples
+
+```javascript
+
+const headers = {
+  'Accept':'application/json'
+};
+
+fetch('http://localhost:3334/api/v1/buckets',
+{
+  method: 'GET',
+
+  headers: headers
+})
+.then(function(res) {
+    return res.json();
+}).then(function(body) {
+    console.log(body);
+});
+
+```
+
+```shell
+# You can also use wget
+curl -X GET http://localhost:3334/api/v1/buckets \
+  -H 'Accept: application/json'
+
+```
+
+`GET /buckets`
+
+Returns list of distributed buckets
+
+> Example responses
+
+> 200 Response
+
+```json
+{
+  "bucketIds": [
+    0
+  ]
+}
+```
+
+<h3 id="public.buckets-responses">Responses</h3>
+
+|Status|Meaning|Description|Schema|
+|---|---|---|---|
+|200|[OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)|OK|[BucketsResponse](#schemabucketsresponse)|
+|500|[Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)|Unexpected server error|None|
+
+<aside class="success">
+This operation does not require authentication
+</aside>
+
+## public.assetHead
+
+<a id="opIdpublic.assetHead"></a>
+
+> Code samples
+
+```javascript
+
+fetch('http://localhost:3334/api/v1/asset/{objectId}',
+{
+  method: 'HEAD'
+
+})
+.then(function(res) {
+    return res.json();
+}).then(function(body) {
+    console.log(body);
+});
+
+```
+
+```shell
+# You can also use wget
+curl -X HEAD http://localhost:3334/api/v1/asset/{objectId}
+
+```
+
+`HEAD /asset/{objectId}`
+
+Returns asset response headers (cache status, content type and/or length, accepted ranges etc.)
+
+<h3 id="public.assethead-parameters">Parameters</h3>
+
+|Name|In|Type|Required|Description|
+|---|---|---|---|---|
+|objectId|path|string|true|Data Object ID|
+
+<h3 id="public.assethead-responses">Responses</h3>
+
+|Status|Meaning|Description|Schema|
+|---|---|---|---|
+|200|[OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)|Object is supported and should be send on GET request.|None|
+|404|[Not Found](https://tools.ietf.org/html/rfc7231#section-6.5.4)|Data object does not exist.|None|
+|421|[Misdirected request](https://tools.ietf.org/html/rfc7540#section-9.1.2)|Misdirected request. Data object not supported by the node.|None|
+|500|[Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)|Unexpected server error|None|
+
+### Response Headers
+
+|Status|Header|Type|Format|Description|
+|---|---|---|---|---|
+|200|X-Cache|string||Describes cache status of an object. Hit - object is already fully fetched in distributor node's cache. Pending - object is still beeing fetched from the storage node. Miss - object is neither in cache not currently beeing fetched. Fetching from storage node may be triggered.|
+
+<aside class="success">
+This operation does not require authentication
+</aside>
+
+## public.asset
+
+<a id="opIdpublic.asset"></a>
+
+> Code samples
+
+```javascript
+
+const headers = {
+  'Accept':'image/*'
+};
+
+fetch('http://localhost:3334/api/v1/asset/{objectId}',
+{
+  method: 'GET',
+
+  headers: headers
+})
+.then(function(res) {
+    return res.json();
+}).then(function(body) {
+    console.log(body);
+});
+
+```
+
+```shell
+# You can also use wget
+curl -X GET http://localhost:3334/api/v1/asset/{objectId} \
+  -H 'Accept: image/*'
+
+```
+
+`GET /asset/{objectId}`
+
+Returns a media file.
+
+<h3 id="public.asset-parameters">Parameters</h3>
+
+|Name|In|Type|Required|Description|
+|---|---|---|---|---|
+|objectId|path|string|true|Data Object ID|
+
+> Example responses
+
+> 200 Response
+
+> 404 Response
+
+```json
+{
+  "type": "string",
+  "message": "string"
+}
+```
+
+<h3 id="public.asset-responses">Responses</h3>
+
+|Status|Meaning|Description|Schema|
+|---|---|---|---|
+|200|[OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)|Full available object data sent|string|
+|206|[Partial Content](https://tools.ietf.org/html/rfc7233#section-4.1)|Requested partial object data sent|string|
+|404|[Not Found](https://tools.ietf.org/html/rfc7231#section-6.5.4)|Data object does not exist.|[ErrorResponse](#schemaerrorresponse)|
+|421|[Misdirected request](https://tools.ietf.org/html/rfc7540#section-9.1.2)|Misdirected request. Data object not supported.|[ErrorResponse](#schemaerrorresponse)|
+|500|[Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)|Unexpected server error|None|
+
+### Response Headers
+
+|Status|Header|Type|Format|Description|
+|---|---|---|---|---|
+|200|X-Cache|string||Describes cache status of an object. Hit - object is already fully fetched in distributor node's cache. Pending - object is still beeing fetched from the storage node. Miss - object is neither in cache not currently beeing fetched. Fetching from storage node may be triggered.|
+|200|X-Data-Source|string||Describes the source of data stream. External - the request was proxied to a storage node. Local - the data is streamed from local file.|
+|206|X-Cache|string||Describes cache status of an object. Hit - object is already fully fetched in distributor node's cache. Pending - object is still beeing fetched from the storage node. Miss - object is neither in cache not currently beeing fetched. Fetching from storage node may be triggered.|
+|206|X-Data-Source|string||Describes the source of data stream. External - the request was proxied to a storage node. Local - the data is streamed from local file.|
+
+<aside class="success">
+This operation does not require authentication
+</aside>
+
+# Schemas
+
+<h2 id="tocS_ErrorResponse">ErrorResponse</h2>
+
+<a id="schemaerrorresponse"></a>
+<a id="schema_ErrorResponse"></a>
+<a id="tocSerrorresponse"></a>
+<a id="tocserrorresponse"></a>
+
+```json
+{
+  "type": "string",
+  "message": "string"
+}
+
+```
+
+### Properties
+
+|Name|Type|Required|Restrictions|Description|
+|---|---|---|---|---|
+|type|string|false|none|none|
+|message|string|true|none|none|
+
+<h2 id="tocS_StatusResponse">StatusResponse</h2>
+
+<a id="schemastatusresponse"></a>
+<a id="schema_StatusResponse"></a>
+<a id="tocSstatusresponse"></a>
+<a id="tocsstatusresponse"></a>
+
+```json
+{
+  "id": "string",
+  "objectsInCache": 0,
+  "storageLimit": 0,
+  "storageUsed": 0,
+  "uptime": 0,
+  "downloadsInProgress": 0
+}
+
+```
+
+### Properties
+
+|Name|Type|Required|Restrictions|Description|
+|---|---|---|---|---|
+|id|string|true|none|none|
+|objectsInCache|integer|true|none|none|
+|storageLimit|integer|true|none|none|
+|storageUsed|integer|true|none|none|
+|uptime|integer|true|none|none|
+|downloadsInProgress|integer|true|none|none|
+
+<h2 id="tocS_BucketsResponse">BucketsResponse</h2>
+
+<a id="schemabucketsresponse"></a>
+<a id="schema_BucketsResponse"></a>
+<a id="tocSbucketsresponse"></a>
+<a id="tocsbucketsresponse"></a>
+
+```json
+{
+  "bucketIds": [
+    0
+  ]
+}
+
+```
+
+### Properties
+
+oneOf
+
+|Name|Type|Required|Restrictions|Description|
+|---|---|---|---|---|
+|*anonymous*|object|false|none|none|
+|» bucketIds|[integer]|true|none|none|
+
+xor
+
+|Name|Type|Required|Restrictions|Description|
+|---|---|---|---|---|
+|*anonymous*|object|false|none|none|
+|» allByWorkerId|integer|true|none|none|
+
+undefined
+

+ 139 - 0
distributor-node/docs/api/templates/main.dot

@@ -0,0 +1,139 @@
+{{= data.tags.section }}
+<h1 id="{{=data.title_prefix}}">{{=data.api.info && data.api.info.title}} {{=data.version}}</h1>
+
+> Scroll down for {{? data.header.language_tabs.length}}code samples, {{?}}example requests and responses.
+
+{{? data.api.info && data.api.info.description}}{{=data.api.info.description}}{{?}}
+
+{{? data.api.servers }}
+Base URLs:
+{{~data.api.servers :s}}
+* <a href="{{=s.url}}">{{=s.url}}</a>
+{{ for(var v in s.variables) { }}
+    * **{{=v}}** - {{=s.variables[v].description||''}} Default: {{=s.variables[v].default}}
+{{? s.variables[v].enum}}
+{{~ s.variables[v].enum :e}}
+        * {{= e}}
+{{~}}
+{{?}}
+{{ } }}
+{{~}}
+{{?}}
+
+{{? data.api.info && data.api.info.termsOfService}}<a href="{{=data.api.info.termsOfService}}">Terms of service</a>{{?}}
+{{? data.api.info && data.api.info.contact}}{{? data.api.info.contact.email}}Email: <a href="mailto:{{=data.api.info.contact.email}}">{{=data.api.info.contact.name || 'Support'}}</a> {{?}}{{? data.api.info.contact.url}}Web: <a href="{{=data.api.info.contact.url}}">{{= data.api.info.contact.name || 'Support'}}</a> {{?}}{{?}}
+{{? data.api.info && data.api.info.license}}{{? data.api.info.license.url}}License: <a href="{{=data.api.info.license.url}}">{{=data.api.info.license.name}}</a>{{??}} License: {{=data.api.info.license.name}}{{?}}{{?}}
+{{= data.tags.endSection }}
+
+{{? data.api.components && data.api.components.securitySchemes }}
+{{#def.security}}
+{{?}}
+
+{{ for (var r in data.resources) { }}
+{{ data.resource = data.resources[r]; }}
+
+{{= data.tags.section }}
+<h1 id="{{=data.title_prefix+'-'+data.utils.slugify(r)}}">{{= r}}</h1>
+
+{{? data.resource.description }}{{= data.resource.description}}{{?}}
+
+{{? data.resource.externalDocs}}
+<a href="{{=data.resource.externalDocs.url}}">{{=data.resource.externalDocs.description||'External documentation'}}</a>
+{{?}}
+
+{{ for (var m in data.resource.methods) { }}
+{{ data.operationUniqueName = m; }}
+{{ data.method = data.resource.methods[m]; }}
+{{ data.operationUniqueSlug = data.method.slug; }}
+{{ data.operation = data.method.operation; }}
+{{= data.templates.operation(data) }}
+{{ } /* of methods */ }}
+
+{{= data.tags.endSection }}
+{{ } /* of resources */ }}
+
+{{? data.api.components && data.api.components.schemas }}
+{{= data.tags.section }}
+
+# Schemas
+
+{{ for (var s in data.components.schemas) { }}
+{{ var origSchema = data.components.schemas[s]; }}
+{{ var schema = data.api.components.schemas[s]; }}
+
+{{= data.tags.section }}
+<h2 id="tocS_{{=s}}">{{=s}}</h2>
+{{ /* backwards compatibility */ }}
+<a id="schema{{=s.toLowerCase()}}"></a>
+<a id="schema_{{=s}}"></a>
+<a id="tocS{{=s.toLowerCase()}}"></a>
+<a id="tocs{{=s.toLowerCase()}}"></a>
+
+{{? data.options.yaml }}
+```yaml
+{{=data.utils.yaml.stringify(data.utils.getSample(schema,data.options,{quiet:true},data.api))}}
+{{??}}
+```json
+{{=data.utils.safejson(data.utils.getSample(schema,data.options,{quiet:true},data.api),null,2)}}
+{{?}}
+```
+
+{{ var enums = []; }}
+{{ var blocks = data.utils.schemaToArray(origSchema,-1,{trim:true,join:true},data); }}
+{{ for (var block of blocks) {
+     for (var p of block.rows) {
+       if (p.schema && p.schema.enum) {
+         for (var e of p.schema.enum) {
+           enums.push({name:p.name,value:e});
+         }
+       }
+     }
+   }
+}}
+
+{{~ blocks :block}}
+{{? block.title }}{{= block.title}}{{= '\n\n'}}{{?}}
+{{? block.externalDocs}}
+<a href="{{=block.externalDocs.url}}">{{=block.externalDocs.description||'External documentation'}}</a>
+{{?}}
+
+{{? block===blocks[0] }}
+{{= data.tags.section }}
+
+### Properties
+{{?}}
+
+{{? block.rows.length}}|Name|Type|Required|Restrictions|Description|
+|---|---|---|---|---|{{?}}
+{{~ block.rows :p}}|{{=p.displayName}}|{{=p.safeType}}|{{=p.required}}|{{=p.restrictions||'none'}}|{{=p.description||'none'}}|
+{{~}}
+{{~}}
+{{? (blocks[0].rows.length === 0) && (blocks.length === 1) }}
+*None*
+{{?}}
+
+{{? enums.length > 0 }}
+{{= data.tags.section }}
+
+#### Enumerated Values
+
+|Property|Value|
+|---|---|
+{{~ enums :e}}|{{=e.name}}|{{=data.utils.toPrimitive(e.value)}}|
+{{~}}
+
+{{= data.tags.endSection }}
+{{?}}
+
+{{= data.tags.endSection }}
+{{= data.tags.endSection }}
+
+{{ } /* of schemas */ }}
+
+{{?}}
+
+{{#def.footer}}
+
+{{? data.options.discovery}}
+{{#def.discovery}}
+{{?}}

+ 48 - 0
distributor-node/docs/commands/dev.md

@@ -0,0 +1,48 @@
+`joystream-distributor dev`
+===========================
+
+
+
+* [`joystream-distributor dev:batchUpload`](#joystream-distributor-devbatchupload)
+* [`joystream-distributor dev:init`](#joystream-distributor-devinit)
+
+## `joystream-distributor dev:batchUpload`
+
+```
+undefined
+
+USAGE
+  $ joystream-distributor dev:batchUpload
+
+OPTIONS
+  -B, --bucketId=bucketId          (required) Storage bucket id
+  -C, --batchesCount=batchesCount  (required)
+  -S, --batchSize=batchSize        (required)
+  -b, --bagId=bagId                (required)
+
+  -c, --configPath=configPath      [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                                   directory)
+
+  -y, --yes                        Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/dev/batchUpload.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/dev/batchUpload.ts)_
+
+## `joystream-distributor dev:init`
+
+Initialize development environment. Sets Alice as distributor working group leader.
+
+```
+Initialize development environment. Sets Alice as distributor working group leader.
+
+USAGE
+  $ joystream-distributor dev:init
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/dev/init.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/dev/init.ts)_

+ 25 - 0
distributor-node/docs/commands/help.md

@@ -0,0 +1,25 @@
+`joystream-distributor help`
+============================
+
+display help for joystream-distributor
+
+* [`joystream-distributor help [COMMAND]`](#joystream-distributor-help-command)
+
+## `joystream-distributor help [COMMAND]`
+
+display help for joystream-distributor
+
+```
+display help for <%= config.bin %>
+
+USAGE
+  $ joystream-distributor help [COMMAND]
+
+ARGUMENTS
+  COMMAND  command to show help for
+
+OPTIONS
+  --all  see all commands in CLI
+```
+
+_See code: [@oclif/plugin-help](https://github.com/oclif/plugin-help/blob/v2.2.3/src/commands/help.ts)_

+ 367 - 0
distributor-node/docs/commands/leader.md

@@ -0,0 +1,367 @@
+`joystream-distributor leader`
+==============================
+
+Cancel pending distribution bucket operator invitation.
+  Requires distribution working group leader permissions.
+
+* [`joystream-distributor leader:cancel-invitation`](#joystream-distributor-leadercancel-invitation)
+* [`joystream-distributor leader:create-bucket`](#joystream-distributor-leadercreate-bucket)
+* [`joystream-distributor leader:create-bucket-family`](#joystream-distributor-leadercreate-bucket-family)
+* [`joystream-distributor leader:delete-bucket`](#joystream-distributor-leaderdelete-bucket)
+* [`joystream-distributor leader:delete-bucket-family`](#joystream-distributor-leaderdelete-bucket-family)
+* [`joystream-distributor leader:invite-bucket-operator`](#joystream-distributor-leaderinvite-bucket-operator)
+* [`joystream-distributor leader:remove-bucket-operator`](#joystream-distributor-leaderremove-bucket-operator)
+* [`joystream-distributor leader:set-bucket-family-metadata`](#joystream-distributor-leaderset-bucket-family-metadata)
+* [`joystream-distributor leader:set-buckets-per-bag-limit`](#joystream-distributor-leaderset-buckets-per-bag-limit)
+* [`joystream-distributor leader:update-bag`](#joystream-distributor-leaderupdate-bag)
+* [`joystream-distributor leader:update-bucket-mode`](#joystream-distributor-leaderupdate-bucket-mode)
+* [`joystream-distributor leader:update-bucket-status`](#joystream-distributor-leaderupdate-bucket-status)
+* [`joystream-distributor leader:update-dynamic-bag-policy`](#joystream-distributor-leaderupdate-dynamic-bag-policy)
+
+## `joystream-distributor leader:cancel-invitation`
+
+Cancel pending distribution bucket operator invitation.
+
+```
+Cancel pending distribution bucket operator invitation.
+  Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:cancel-invitation
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket id
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -f, --familyId=familyId      (required) Distribution bucket family id
+
+  -w, --workerId=workerId      (required) ID of the invited operator (distribution group worker)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+
+DESCRIPTION
+  Requires distribution working group leader permissions.
+```
+
+_See code: [src/commands/leader/cancel-invitation.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/cancel-invitation.ts)_
+
+## `joystream-distributor leader:create-bucket`
+
+Create new distribution bucket. Requires distribution working group leader permissions.
+
+```
+Create new distribution bucket. Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:create-bucket
+
+OPTIONS
+  -a, --acceptingBags=(yes|no)  [default: no] Whether the created bucket should accept new bags
+
+  -c, --configPath=configPath   [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                                directory)
+
+  -f, --familyId=familyId       (required) Distribution bucket family id
+
+  -y, --yes                     Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/leader/create-bucket.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/create-bucket.ts)_
+
+## `joystream-distributor leader:create-bucket-family`
+
+Create new distribution bucket family. Requires distribution working group leader permissions.
+
+```
+Create new distribution bucket family. Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:create-bucket-family
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/leader/create-bucket-family.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/create-bucket-family.ts)_
+
+## `joystream-distributor leader:delete-bucket`
+
+Delete distribution bucket. The bucket must have no operators. Requires distribution working group leader permissions.
+
+```
+Delete distribution bucket. The bucket must have no operators. Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:delete-bucket
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket id
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -f, --familyId=familyId      (required) Distribution bucket family id
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/leader/delete-bucket.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/delete-bucket.ts)_
+
+## `joystream-distributor leader:delete-bucket-family`
+
+Delete distribution bucket family. Requires distribution working group leader permissions.
+
+```
+Delete distribution bucket family. Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:delete-bucket-family
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -f, --familyId=familyId      (required) Distribution bucket family id
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/leader/delete-bucket-family.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/delete-bucket-family.ts)_
+
+## `joystream-distributor leader:invite-bucket-operator`
+
+Invite distribution bucket operator (distribution group worker).
+
+```
+Invite distribution bucket operator (distribution group worker).
+  The specified bucket must not have any operator currently.
+  Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:invite-bucket-operator
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket id
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -f, --familyId=familyId      (required) Distribution bucket family id
+
+  -w, --workerId=workerId      (required) ID of the distribution group worker to invite as bucket operator
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+
+DESCRIPTION
+  The specified bucket must not have any operator currently.
+     Requires distribution working group leader permissions.
+```
+
+_See code: [src/commands/leader/invite-bucket-operator.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/invite-bucket-operator.ts)_
+
+## `joystream-distributor leader:remove-bucket-operator`
+
+Remove distribution bucket operator (distribution group worker).
+
+```
+Remove distribution bucket operator (distribution group worker).
+  Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:remove-bucket-operator
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket id
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -f, --familyId=familyId      (required) Distribution bucket family id
+
+  -w, --workerId=workerId      (required) ID of the operator (distribution working group worker) to remove from the
+                               bucket
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+
+DESCRIPTION
+  Requires distribution working group leader permissions.
+```
+
+_See code: [src/commands/leader/remove-bucket-operator.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/remove-bucket-operator.ts)_
+
+## `joystream-distributor leader:set-bucket-family-metadata`
+
+Set/update distribution bucket family metadata.
+
+```
+Set/update distribution bucket family metadata.
+  Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:set-bucket-family-metadata
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -f, --familyId=familyId      (required) Distribution bucket family id
+
+  -i, --input=input            (required) Path to JSON metadata file
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+
+DESCRIPTION
+  Requires distribution working group leader permissions.
+```
+
+_See code: [src/commands/leader/set-bucket-family-metadata.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/set-bucket-family-metadata.ts)_
+
+## `joystream-distributor leader:set-buckets-per-bag-limit`
+
+Set max. distribution buckets per bag limit. Requires distribution working group leader permissions.
+
+```
+Set max. distribution buckets per bag limit. Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:set-buckets-per-bag-limit
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -l, --limit=limit            (required) New limit value
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/leader/set-buckets-per-bag-limit.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/set-buckets-per-bag-limit.ts)_
+
+## `joystream-distributor leader:update-bag`
+
+Add/remove distribution buckets from a bag.
+
+```
+Add/remove distribution buckets from a bag.
+
+USAGE
+  $ joystream-distributor leader:update-bag
+
+OPTIONS
+  -a, --add=add
+      [default: ] ID of a bucket to add to bag
+
+  -b, --bagId=bagId
+      (required) Bag ID. Format: {bag_type}:{sub_type}:{id}.
+           - Bag types: 'static', 'dynamic'
+           - Sub types: 'static:council', 'static:wg', 'dynamic:member', 'dynamic:channel'
+           - Id:
+             - absent for 'static:council'
+             - working group name for 'static:wg'
+             - integer for 'dynamic:member' and 'dynamic:channel'
+           Examples:
+           - static:council
+           - static:wg:storage
+           - dynamic:member:4
+
+  -c, --configPath=configPath
+      [default: ./config.yml] Path to config JSON/YAML file (relative to current working directory)
+
+  -f, --familyId=familyId
+      (required) ID of the distribution bucket family
+
+  -r, --remove=remove
+      [default: ] ID of a bucket to remove from bag
+
+  -y, --yes
+      Answer "yes" to any prompt, skipping any manual confirmations
+
+EXAMPLE
+  $ joystream-distributor leader:update-bag -b 1 -f 1 -a 1 -a 2 -a 3 -r 4 -r 5
+```
+
+_See code: [src/commands/leader/update-bag.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/update-bag.ts)_
+
+## `joystream-distributor leader:update-bucket-mode`
+
+Update distribution bucket mode ("distributing" flag). Requires distribution working group leader permissions.
+
+```
+Update distribution bucket mode ("distributing" flag). Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:update-bucket-mode
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket id
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -d, --mode=(on|off)          (required) Whether the bucket should be "on" (distributing) or "off" (not distributing)
+
+  -f, --familyId=familyId      (required) Distribution bucket family id
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/leader/update-bucket-mode.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/update-bucket-mode.ts)_
+
+## `joystream-distributor leader:update-bucket-status`
+
+Update distribution bucket status ("acceptingNewBags" flag). Requires distribution working group leader permissions.
+
+```
+Update distribution bucket status ("acceptingNewBags" flag). Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:update-bucket-status
+
+OPTIONS
+  -B, --bucketId=bucketId       (required) Distribution bucket id
+  -a, --acceptingBags=(yes|no)  (required) Whether the bucket should accept new bags
+
+  -c, --configPath=configPath   [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                                directory)
+
+  -f, --familyId=familyId       (required) Distribution bucket family id
+
+  -y, --yes                     Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/leader/update-bucket-status.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/update-bucket-status.ts)_
+
+## `joystream-distributor leader:update-dynamic-bag-policy`
+
+Update dynamic bag creation policy (number of buckets by family that should store given dynamic bag type).
+
+```
+Update dynamic bag creation policy (number of buckets by family that should store given dynamic bag type).
+    Requires distribution working group leader permissions.
+
+USAGE
+  $ joystream-distributor leader:update-dynamic-bag-policy
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -p, --policy=policy          Key-value pair of {familyId}:{numberOfBuckets}
+
+  -t, --type=(Member|Channel)  (required) Dynamic bag type
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+
+DESCRIPTION
+  Requires distribution working group leader permissions.
+
+EXAMPLE
+  $ joystream-distributor leader:update-dynamic-bag-policy -t Member -p 1:5 -p 2:10 -p 3:5
+```
+
+_See code: [src/commands/leader/update-dynamic-bag-policy.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/leader/update-dynamic-bag-policy.ts)_

+ 70 - 0
distributor-node/docs/commands/operator.md

@@ -0,0 +1,70 @@
+`joystream-distributor operator`
+================================
+
+Accept pending distribution bucket operator invitation.
+  Requires the invited distribution group worker role key.
+
+* [`joystream-distributor operator:accept-invitation`](#joystream-distributor-operatoraccept-invitation)
+* [`joystream-distributor operator:set-metadata`](#joystream-distributor-operatorset-metadata)
+
+## `joystream-distributor operator:accept-invitation`
+
+Accept pending distribution bucket operator invitation.
+
+```
+Accept pending distribution bucket operator invitation.
+  Requires the invited distribution group worker role key.
+
+USAGE
+  $ joystream-distributor operator:accept-invitation
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket id
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -f, --familyId=familyId      (required) Distribution bucket family id
+
+  -w, --workerId=workerId      (required) ID of the invited operator (distribution group worker)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+
+DESCRIPTION
+  Requires the invited distribution group worker role key.
+```
+
+_See code: [src/commands/operator/accept-invitation.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/operator/accept-invitation.ts)_
+
+## `joystream-distributor operator:set-metadata`
+
+Set/update distribution bucket operator metadata.
+
+```
+Set/update distribution bucket operator metadata.
+  Requires active distribution bucket operator worker role key.
+
+USAGE
+  $ joystream-distributor operator:set-metadata
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket id
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -e, --endpoint=endpoint      Root distribution node endpoint
+
+  -f, --familyId=familyId      (required) Distribution bucket family id
+
+  -i, --input=input            Path to JSON metadata file
+
+  -w, --workerId=workerId      (required) ID of the operator (distribution group worker)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+
+DESCRIPTION
+  Requires active distribution bucket operator worker role key.
+```
+
+_See code: [src/commands/operator/set-metadata.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/operator/set-metadata.ts)_

+ 25 - 0
distributor-node/docs/commands/start.md

@@ -0,0 +1,25 @@
+`joystream-distributor start`
+=============================
+
+Start the node
+
+* [`joystream-distributor start`](#joystream-distributor-start)
+
+## `joystream-distributor start`
+
+Start the node
+
+```
+Start the node
+
+USAGE
+  $ joystream-distributor start
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/start.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/start.ts)_

+ 343 - 0
distributor-node/docs/node/index.md

@@ -0,0 +1,343 @@
+<a name="the-api"></a>
+
+# The API
+
+The Distributor Node exposes an HTTP api implemented with [ExpressJS](https://expressjs.com/).
+
+The api is described by an [OpenAPI](https://swagger.io/specification/) schema located at _[src/api-spec/openapi.yml](../../src/api-spec/openapi.yml)_
+
+Current, detailed api documentation can be found [here](../api/index.md)
+
+<a name="requesting-assets"></a>
+
+## Requesting assets
+
+The assets are requested from the distributor node by using a `GET` request to [`/asset/{objectId}`](../api/index.md#opIdpublic.asset) endpoint.
+
+There are multiple scenarios of how a distributor will act upon that request, depending on its current state:
+
+<a name="scenario-1"></a>
+
+### Scenario 1 (cache hit)
+
+**The requested data object is already available in the distributor node's filesystem (cache)**
+
+In this case:
+- Object's LRU-SP cache state is updated (see Caching policy for more details)
+- The [`send`](https://www.npmjs.com/package/send) library is used to handle the request and serve the object. The library supports partial responses (Ranges), conditional-GET negotiation (If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since) and much more.
+- `x-cache: hit` and `x-data-source: local` headers are sent, providing the client detailed information about the triggered scenario.
+- `cache-control: max-age` is set to `31536000` (one year), which is a common practice for informing the browser that the object can essentially be cached "forever" (minimizing the number of request for the same data object)
+
+<a name="scenario-2"></a>
+
+### Scenario 2 (pending)
+
+**The object is not yet cached, but is currently being fetched from the storage node**
+
+In this case `cache-control: max-age` is set to a substantially lower value (currently `180`), as the distributor node cannot yet confirm whether the object being fetched is indeed valid.
+
+<a name="scenario-2-1"></a>
+
+#### Scenario 2.1: No `Range` header was provided or the `Range` start is `<= partiallyDownloadedContentSize`
+
+In this case:
+
+- The data is streamed into the response from the local, partially downloaded file. All the data that gets written to the local file, as it's being downloaded from the storage node, is immediately pushed into the http response.
+- `x-cache: pending` and `x-data-source: local` headers are sent, providing the client detailed information about the triggered scenario.
+
+<a name="scenario-2-2"></a>
+
+#### Scenario 2.2: `Range` header was provided and `Range` start is `> partiallyDownloadedContentSize`
+
+In this case streaming the response from partially downloaded file, like in scenario above, may cause unnecessary delay, since the requested `Range` may target the very end of the file, which will only be available locally once the entire data object is fetched. That's why in this case:
+- The request is forwarded to the storage node that the data object is currently being downloaded from using [express-http-proxy](https://www.npmjs.com/package/express-http-proxy)
+- `x-cache: pending` and `x-data-source: external` headers are sent, providing the client detailed information about the triggered scenario.
+
+<a name="scenario-3"></a>
+### Scenario 3 (cache miss)
+
+In this case the distributor node is making a request to query node to fetch details of the requested object like:
+- content hash,
+- object size,
+- storage buckets assigned to store the object,
+- distribution buckets assigned to distribute the object
+
+It then proceeds to one of the following scenarios:
+
+<a name="scenario-3-1"></a>
+
+#### Scenario 3.1: The requested data object is not found
+
+Node responds with `HTTP 404 (Not Found)` and a message
+
+<a name="scenario-3-2"></a>
+
+#### Scenario 3.2: The object is not distributed by the node
+
+Node responds with `HTTP 421 (Misdirected Request)` and a message
+
+<a name="scenario-3-3"></a>
+
+#### Scenario 3.3: The request is valid, the node needs to fetch the missing object
+
+In this case
+- The process of fetching the data object from storage node described in the [Data fetching](#data-fetching) section below is triggered.
+- Once the storage node from which the object is going to be fetched is chosen, the request is handled in a way analogous to the one described in [Scenario 2](#scenario-2), with the exception that `x-cache: miss` header will be sent instead of `x-cache: pending`.
+
+<a name="checking-asset-status"></a>
+
+## Checking asset status
+
+It is possible to check the asset status without triggering given scenario (for example - the process of fetching the missing data object) by sending a [`HEAD` request to `/asset/{objectId}`](../api/index.md#opIdpublic.assetHead) endpoint.
+
+If the request is valid, the node will send, among others, the `x-cache`, `content-length`, `cache-control` headers.
+
+In case of an invalid request, the node will respond with the same status it would in case of a `GET` request.
+
+<a name="api-limits"></a>
+
+## API limits
+
+There are no rate / connection limits on incoming requests enforced by the node, it is therefore recommended to use a firewall or reverse proxy in order to protect the node from DOS/DDOS attacks.
+
+The outbound connections (from distributor node to storage nodes) can be limited with [`limits`](../schema/definition-properties-limits.md) configuration settings.
+
+<a name="example-nginx-configuration"></a>
+
+### Example Nginx configuration
+
+```
+upstream distributor {
+    server 127.0.0.1:3334;
+}
+
+http {
+  # Create a conn_perip zone that will keep track of concurrent connections by ip
+  limit_conn_zone $binary_remote_addr zone=conn_perip:10m;
+
+  server {
+    server_name example-distributor-node;
+    listen 443;
+
+    # Limit to max 20 connections per ip at a time
+    limit_conn addr 20;
+
+    location / {
+      proxy_pass http://distributor/;
+      proxy_http_version 1.1;
+      proxy_set_header Upgrade $http_upgrade;
+      proxy_set_header Connection "upgrade";
+      proxy_set_header Host $http_host;
+
+      proxy_set_header X-Real-IP $remote_addr;
+      proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
+      proxy_set_header X-Forward-Proto http;
+      proxy_set_header X-Nginx-Proxy true;
+
+        proxy_redirect off;
+    }
+
+    # SSL and other configuration...
+  }
+}
+```
+
+Because Nginx does not support [HTTP pipelining](https://en.wikipedia.org/wiki/HTTP_pipelining), by limiting the number of concurrent connections per ip we also limit the number of data objects that can be concurrently fetched from the distributor node by a single IP.
+
+Having in mind that [most browsers will not make more than 6 concurrent connections](https://docs.pushtechnology.com/cloud/latest/manual/html/designguide/solution/support/connection_limitations.html), the limit of `20` concurrent connections per ip should be more than sufficient.
+
+<a name="system-configuration"></a>
+
+### System configuration
+
+When configuring the limits important to keep in mind that when handling a lot of simultaneous connections some system limitation may be hit.
+
+For example, the default limit of file descriptors a single process can open on Linux systems is `1024`. If left unchanged, this limit can easily cause problems, as this means only `1024` connections can be handled concurrently. In reality this number will be much lower for distributor node, because:
+- Each connection will require 1 file descriptor for a socket
+- Each incoming connection will most likely require an asset (data object) file to be accessed, which will take another descriptor,
+- Each incoming connection may trigger many outbound connections (see [Data fetching](#data-fetching) section below) in case of cache miss, in worst case taking over 10 more descriptors
+
+For Linux users it is recommended to either run the distributor node using the docker image, which already has high limits set, or [modify the max open file descriptors limit manually](https://docs.oracle.com/cd/E19623-01/820-6168/file-descriptor-requirements.html)
+
+<a name="data-fetching"></a>
+
+# Data fetching
+
+<a name="finding-nearby-storage-nodes"></a>
+
+## Finding nearby storage nodes:
+
+In order to limit the number of requests being made on cache miss and the time it takes to fetch a new object [in this scenario](#scenario-3), the distributor node needs to keep track of how quickly (on average) the currently available storage nodes are responding to requests.
+
+This can be partially solved by making use of the on-chain metadata provided by storage node operators, which may include details about the node location (see [Metadata](#metadata) section) that can provide some estimation of which nodes will likely respond faster. However, because this approach is quite limited and it's possible that most storage providers will choose not to expose their node location, the distributor node instead uses a different approach to find nearby nodes.
+
+Currently the distributor node periodically (every [`intervals.checkStorageNodeResponseTimes`](../schema/definition-properties-intervals-properties-checkstoragenoderesponsetimes.md) seconds) fetches all active storage provider endpoints (from the query node) and measures their average response times to `/status/version` requests. This is done independently of any incoming requests. The "response time check" requests are queued using relatively small concurrency limit (10) in order to make the cost of this operation minimal.
+
+This provides a pretty good estimation on which nodes will likely be the best candidates for fetching data objects during a cache miss, it also allows filtering-out storage nodes that don't respond at all or respond with an error.
+
+<a name="data-object-fetching-flow"></a>
+
+## Data object fetching flow
+
+During the [cache miss scenario (`Scenario 3.3`)](#scenario-3-3), the following tasks are executed:
+
+First, the endpoints of all storage providers that are supposed to store the given object are ordered by the mean response time using 10 last response times (the process of obtaining those measurements is described in the [previous section](#finding-nearby-storage-nodes))
+
+The `HEAD /files/{objectId}` requests are then sent to the storage endpoints, starting from the ones with lowest mean response time. Those initial requests are only meant to determine whether a given storage node can indeed serve the object. In fact, all those requests are put (in the specified order) in the `availabilityCheckQueue` which then executes them with a constant maximum concurrency (`10` at the time of writing).
+
+As soon as any storage node confirms the availability of the object, the `availabilityCheckQueue` is temporarily stopped and `GET /files/{objectId}` request is made to fetch the full data from the selected provider. Because the distributor node uses `Connection: keep-alive` headers when sending requests to storage nodes, there's no need to re-establish a TCP connection at this point, which can save a considerable amount of time. If other storage providers confirm the availability of the object during this time, other `GET` requests will be added to `objectDownloadQueue` (which uses a concurrency of 1), allowing the distributor node to instantly try a different provider in case the first `GET` request fails. The process continues until a storage node that responds with `HTTP 200` to a `GET` request is found.
+
+Once some storage node responds with `HTTP 200` and starts streaming the data, all other requests related to that data object are stopped and the distributor node begins to write the data into its filesystem. Any errors at this point (unexpected data size, stream errors) will mean that the fetching process has failed, causing the data object and any related state to be dropped and the whole process of fetching the object to potentially be repeated upon another request.
+
+<a name="metadata"></a>
+
+# Metadata
+
+The documentation of current storage&distribution system on-chain metadata standard can be found [here](../../../metadata-protobuf/doc/index.md#proto/Storage.proto)
+
+[Distributor node metadata](#distribution-bucket-operator-metadata) can be set using [`operator:set-metadata`](../commands/operator.md#joystream-distributor-operatorset-metadata) command in Distributor Node CLI.
+
+[Distribution family metadata](#distribution-bucket-family-metadata) can be set using [`leader:set-bucket-family-metadata](../commands/leader.md#joystream-distributor-leaderset-bucket-family-metadata)
+
+Once set, the metadata can be accessed from the Query Node with a GraphQL query like, for example:
+```graphql
+query {
+  distributionBuckets {
+    family {
+      metadata {
+        region
+        description
+        areas {
+          continent
+          countryCode
+          subdivisionCode
+        }
+        latencyTestTargets
+      }
+    }
+    operators {
+      metadata {
+        nodeEndpoint
+        nodeLocation {
+          countryCode
+          coordinates {
+            latitude
+            longitude
+          }
+        }
+        extra
+      }
+    }
+  }
+}
+```
+
+<a name="distribution-bucket-family-metadata"></a>
+
+## DistributionBucketFamilyMetadata
+
+The main purpose of distribution family metadata is to help client (frontend) applications find out which distribution nodes should be preferred when fetching assets.
+
+Although each node operator may choose to expose its own node location in the [DistributionBucketOperatorMetadata](#distribution-bucket-operator-metadata), it is generally assumed that all nodes belonging to a given family will have a decent latency in the region covered by this family, so they can be treated more-or-less equally.
+
+What exactly constitutes a `region` in the `DistributionBucketFamilyMetadata` is not strictly enforced and the current metadata standard remains quite flexible in that regard.
+
+<a name="geographical-areas-covered-by-the-distirbution-bucket-family"></a>
+
+### Geographical areas covered by the distirbution bucket family
+
+Initially, as the number of distribution nodes will probably be limited, a region can mean a relatively large geographic area (ie. a continent or part of a continent). Later, as the network grows, the region may mean a single country / subdivision or a small set of nearby countries / subdivisions.
+
+In order to support all those cases, the `areas` field in the `DistributionBucketFamilyMetadata` allows specifying either one or multiple geographical areas covered by the family, where each area can be either:
+- a continent uniquely identified by `Continent` enum value, _or_
+- a country uniquely identified by [`ISO-3166-1 alpha-2`](https://en.wikipedia.org/wiki/ISO_3166-2) country code, _or_
+- a subdivision (for example, a state) uniquely identified by [`ISO_3166-2`](https://en.wikipedia.org/wiki/ISO_3166-2) subdivision code
+
+There are multiple ways client applications may be able to determine most suitable regions:
+
+- Using [`HTML5 geolocation API`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) and reverse geocoding (which can be done either using a local dataset, custom backend or an external service)
+- using GeoDNS or a backend service to establish the approximate location before rendering the interface
+- Prompting the user to manually provide the preferred region
+
+<a name="using-latency-tests-for-choosing-a-family"></a>
+
+### Using latency tests for choosing a family
+
+Another way to choose the most appropriate region may be to perform an initial latency check by pinging endpoints that are supposed to give the most representative results for given family (for example, [https://www.cloudping.info/] can perform such measurements using endpoints that represent AWS regions).
+
+In order to facilitate this, `latency_test_targets` field in the `DistributionBucketFamilyMetadata` allows specifying the list of representative ips / hosts to be used for such measurements. Alternatively a chosen set of distribution nodes themselves may also be used.
+
+<a name="distribution-bucket-operator-metadata"></a>
+
+## Distribution bucket operator metadata
+
+The most essential part of `DistributionBucketOperatorMetadata` is the node API root endpoint, it must be provided by all active node operators, otherwise no app will be able to access the node.
+
+The node operator may optionally choose to expose more details about the node, like specific `location` metadata or some additional `extra` information.
+
+<a name="state"></a>
+
+# State
+
+The distributor node state is divided into memory state and persistent state.
+
+Most of the state is managed via via an "intermediary" service called [`StateCacheService`](../../src/services/cache/StateCacheService.ts). This is to facilitate the potential migration to other state management approaches, like using `Redis` in the future. Currently the service automatically saves the persistent state to the filesystem every [`intervals.saveCacheState`](../schema/definition-properties-intervals-properties-savecachestate.md) seconds. It also tries to save the state every time the node is exiting.
+
+The current state includes:
+
+**Memory state**
+- `pendingDownloadsByObjectId` map - stores information about currently pending downloads (data object fetching attempts). Each pending download can be in one of the following states:
+  - `Waiting` - in case [`limits.maxConcurrentStorageNodeDownloads`](../schema/definition-properties-limits-properties-maxconcurrentstoragenodedownloads.md) limit is reached, this is the status of pending downloads that are waiting in the queue. It is also the initial status of all pending downloads in general.
+  - `LookingForSource` - the process of finding a storage node that is able to serve the asset has started, but the source node has not yet been chosen.
+  - `Downloading` - the source storage node has been chosen and the data object is being downloaded.
+- `storageNodeEndpointDataByEndpoint` map - currently stores the last 10 average mean response times mapped by storage nodes endpoints (see: [_Finding nearby storage nodes_](#finding-nearby-storage-nodes))
+- `groupNumberByObjectId` map - stores the LRU-SP cache group number (see: [_Caching policy_](#caching-policy)) of each cached data object.
+
+**Persistent state**
+- `lruCacheGroups` - list of LRU-SP cache groups. Each LRU group contains a map of cached data object details (size, popularity, last access time) required to to calculate its `cost` parameter (see: [_Caching policy_](#caching-policy))
+- `mimeTypeByObjectId` map - stores the `mimeType` (as determined by the distributor node) of each cached data object
+
+<a name="caching"></a>
+
+# Caching
+
+<a name="caching-policy"></a>
+
+## Caching policy
+
+The caching policy used for the data objects stored by the distributor node is called **[`LRU-SP`](http://www.is.kyusan-u.ac.jp/~chengk/pub/papers/compsac00_A07-07.pdf)**.
+
+This caching policy was designed specifically for the web and it takes into account the following 3 properties of a data object:
+- object size (`s`)
+- object popularity (number of times it was requested while being cached) (`p`)
+- time elapsed since the object was last requested (`t`)
+
+The cost function of a cache item is described by the formula: `t * s / p`.
+Objects with highest cost are the first to be evicted in case [`limits.storage`](../schema/definition-properties-limits-properties-storage.md) limit is reached.
+
+<a name="lru-groups"></a>
+
+### LRU groups
+
+For efficiency, the cache is divided into `LRU` ([_Least recently used_](https://en.wikipedia.org/wiki/Page_replacement_algorithm#Least_recently_used)) sets (groups) such that all objects in a given group share the same integer value of `log2(s / p)`. In the current distributor node implementation, the unit used for `s` (object size) is `KB` (kilobytes). This means that if we have 24 LRU groups and assume `p = 1` (_popularity = 1_) for all objects, first LRU group will contain objects of size `1 - 2 KB`, second one `2 - 4 KB` etc. up until 24-th group with objects of size `8 - 16 GB` (or `2^23 KB - 2^24 KB`).
+
+When the object is being requested, we're incrementing its `p` and checking the current value of `log2(s / p)`. Then we're calling `SetA.delete(object)` + `SetB.add(object)` (either moving the item to a different LRU set based on current `log2(s / p)`, in which case `SetA` !== `SetB`, or just moving the item to the "top" of the current set, in which case `SetA` === `SetB`). All of those operations are very quick and don't require any costly iterations.
+
+In order to find the best eviction candidate, we're taking the "bottom" item from each LRU set and then choose an element with lowest `t * s / p` (which is also a low-cost operation, considering we need only ~24 LRU groups)
+
+<a name="cache-cleanup"></a>
+
+## Cache cleanup
+
+No-longer-distributed data objects are dropped from the cache periodically every [`intervals.cacheCleanup`](../schema/definition-properties-intervals-properties-cachecleanup.md) seconds. During this time the distributor node will fetch all its current on-chain obligations using the query node and drop any objects that are part of the cache but not part of the obligations from both the cache state and filesystem.
+
+<a name="logging"></a>
+
+# Logging
+
+The distributor node supports detailed logging with [winston](https://www.npmjs.com/package/winston) library. [NPM log levels](https://www.npmjs.com/package/winston#logging-levels) are used to specify the log importance.
+
+The logs can be directed to some of the 3 available outputs, depending on the [`logs`](../schema/definition-properties-directories-logs.md) configuration settings:
+- console
+- a log file inside [`directories.logs`](../schema/definition-properties-directories-logs.md)
+- an elasticsearch endpoint specified via [`endpoints.elasticsearch`](../schema/definition-properties-endpoints-properties-elasticsearch.md)

+ 25 - 0
distributor-node/docs/schema/README.md

@@ -0,0 +1,25 @@
+# README
+
+## Top-level Schemas
+
+*   [Distributor node configuration](./definition.md "Configuration schema for distirubtor CLI and node") – `-`
+
+## Other Schemas
+
+### Objects
+
+*   [Untitled object in Distributor node configuration](./definition-properties-endpoints.md "Specifies external endpoints that the distributor node will connect to") – `undefined#/properties/endpoints`
+
+*   [Untitled object in Distributor node configuration](./definition-properties-directories.md "Specifies paths where node's data will be stored") – `undefined#/properties/directories`
+
+*   [Untitled object in Distributor node configuration](./definition-properties-log.md "Specifies minimum log levels by supported log outputs") – `undefined#/properties/log`
+
+*   [Untitled object in Distributor node configuration](./definition-properties-limits.md "Specifies node limits w") – `undefined#/properties/limits`
+
+*   [Untitled object in Distributor node configuration](./definition-properties-intervals.md "Specifies how often periodic tasks (for example cache cleanup) are executed by the node") – `undefined#/properties/intervals`
+
+### Arrays
+
+*   [Untitled array in Distributor node configuration](./definition-properties-keys.md "Specifies the keys to use within distributor node CLI") – `undefined#/properties/keys`
+
+*   [Untitled array in Distributor node configuration](./definition-properties-buckets-oneof-0.md "List of distribution bucket ids") – `undefined#/properties/buckets/oneOf/0`

+ 7 - 0
distributor-node/docs/schema/definition-properties-buckets-oneof-0-items.md

@@ -0,0 +1,7 @@
+## items Type
+
+`integer`
+
+## items Constraints
+
+**minimum**: the value of this number must greater than or equal to: `0`

+ 7 - 0
distributor-node/docs/schema/definition-properties-buckets-oneof-0.md

@@ -0,0 +1,7 @@
+## 0 Type
+
+`integer[]`
+
+## 0 Constraints
+
+**minimum number of items**: the minimum number of items for this array is: `1`

+ 11 - 0
distributor-node/docs/schema/definition-properties-buckets-oneof-1.md

@@ -0,0 +1,11 @@
+## 1 Type
+
+`string`
+
+## 1 Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value   | Explanation |
+| :------ | :---------- |
+| `"all"` |             |

+ 9 - 0
distributor-node/docs/schema/definition-properties-buckets.md

@@ -0,0 +1,9 @@
+## buckets Type
+
+merged type ([Details](definition-properties-buckets.md))
+
+one (and only one) of
+
+*   [Untitled array in Distributor node configuration](definition-properties-buckets-oneof-0.md "check type definition")
+
+*   [Untitled string in Distributor node configuration](definition-properties-buckets-oneof-1.md "check type definition")

+ 3 - 0
distributor-node/docs/schema/definition-properties-directories-assets.md

@@ -0,0 +1,3 @@
+## assets Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-directories-cachestate.md

@@ -0,0 +1,3 @@
+## cacheState Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-directories-logs.md

@@ -0,0 +1,3 @@
+## logs Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-directories-properties-cache.md

@@ -0,0 +1,3 @@
+## cache Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-directories-properties-data.md

@@ -0,0 +1,3 @@
+## data Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-directories-properties-logs.md

@@ -0,0 +1,3 @@
+## logs Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-directories.md

@@ -0,0 +1,3 @@
+## directories Type
+
+`object` ([Details](definition-properties-directories.md))

+ 3 - 0
distributor-node/docs/schema/definition-properties-endpoints-properties-elasticsearch.md

@@ -0,0 +1,3 @@
+## elasticSearch Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-endpoints-properties-joystreamnodews.md

@@ -0,0 +1,3 @@
+## joystreamNodeWs Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-endpoints-properties-querynode.md

@@ -0,0 +1,3 @@
+## queryNode Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-endpoints-properties-substratenode.md

@@ -0,0 +1,3 @@
+## substrateNode Type
+
+`string`

+ 65 - 0
distributor-node/docs/schema/definition-properties-endpoints.md

@@ -0,0 +1,65 @@
+## endpoints Type
+
+`object` ([Details](definition-properties-endpoints.md))
+
+# endpoints Properties
+
+| Property                            | Type     | Required | Nullable       | Defined by                                                                                                                                                   |
+| :---------------------------------- | :------- | :------- | :------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [queryNode](#querynode)             | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-endpoints-properties-querynode.md "undefined#/properties/endpoints/properties/queryNode")             |
+| [joystreamNodeWs](#joystreamnodews) | `string` | Optional | cannot be null | [Distributor node configuration](definition-properties-endpoints-properties-joystreamnodews.md "undefined#/properties/endpoints/properties/joystreamNodeWs") |
+| [elasticSearch](#elasticsearch)     | `string` | Optional | cannot be null | [Distributor node configuration](definition-properties-endpoints-properties-elasticsearch.md "undefined#/properties/endpoints/properties/elasticSearch")     |
+
+## queryNode
+
+Query node graphql server uri (for example: <http://localhost:8081/graphql>)
+
+`queryNode`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-endpoints-properties-querynode.md "undefined#/properties/endpoints/properties/queryNode")
+
+### queryNode Type
+
+`string`
+
+## joystreamNodeWs
+
+Joystream node websocket api uri (for example: ws\://localhost:9944)
+
+`joystreamNodeWs`
+
+*   is optional
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-endpoints-properties-joystreamnodews.md "undefined#/properties/endpoints/properties/joystreamNodeWs")
+
+### joystreamNodeWs Type
+
+`string`
+
+## elasticSearch
+
+Elasticsearch uri used for submitting the distributor node logs (if enabled via `log.elastic`)
+
+`elasticSearch`
+
+*   is optional
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-endpoints-properties-elasticsearch.md "undefined#/properties/endpoints/properties/elasticSearch")
+
+### elasticSearch Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-id.md

@@ -0,0 +1,3 @@
+## id Type
+
+`string`

+ 7 - 0
distributor-node/docs/schema/definition-properties-intervals-properties-cachecleanup.md

@@ -0,0 +1,7 @@
+## cacheCleanup Type
+
+`integer`
+
+## cacheCleanup Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`

+ 7 - 0
distributor-node/docs/schema/definition-properties-intervals-properties-checkstoragenoderesponsetimes.md

@@ -0,0 +1,7 @@
+## checkStorageNodeResponseTimes Type
+
+`integer`
+
+## checkStorageNodeResponseTimes Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`

+ 7 - 0
distributor-node/docs/schema/definition-properties-intervals-properties-savecachestate.md

@@ -0,0 +1,7 @@
+## saveCacheState Type
+
+`integer`
+
+## saveCacheState Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`

+ 77 - 0
distributor-node/docs/schema/definition-properties-intervals.md

@@ -0,0 +1,77 @@
+## intervals Type
+
+`object` ([Details](definition-properties-intervals.md))
+
+# intervals Properties
+
+| Property                                                        | Type      | Required | Nullable       | Defined by                                                                                                                                                                               |
+| :-------------------------------------------------------------- | :-------- | :------- | :------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [saveCacheState](#savecachestate)                               | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-intervals-properties-savecachestate.md "undefined#/properties/intervals/properties/saveCacheState")                               |
+| [checkStorageNodeResponseTimes](#checkstoragenoderesponsetimes) | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-intervals-properties-checkstoragenoderesponsetimes.md "undefined#/properties/intervals/properties/checkStorageNodeResponseTimes") |
+| [cacheCleanup](#cachecleanup)                                   | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-intervals-properties-cachecleanup.md "undefined#/properties/intervals/properties/cacheCleanup")                                   |
+
+## saveCacheState
+
+How often, in seconds, will the cache state be saved in `directories.state`. Independently of the specified interval, the node will always try to save cache state before exiting.
+
+`saveCacheState`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-intervals-properties-savecachestate.md "undefined#/properties/intervals/properties/saveCacheState")
+
+### saveCacheState Type
+
+`integer`
+
+### saveCacheState Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`
+
+## checkStorageNodeResponseTimes
+
+How often, in seconds, will the distributor node attempt to send requests to all current storage node endpoints in order to check how quickly they respond. The node will never make more than 10 such requests concurrently.
+
+`checkStorageNodeResponseTimes`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-intervals-properties-checkstoragenoderesponsetimes.md "undefined#/properties/intervals/properties/checkStorageNodeResponseTimes")
+
+### checkStorageNodeResponseTimes Type
+
+`integer`
+
+### checkStorageNodeResponseTimes Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`
+
+## cacheCleanup
+
+How often, in seconds, will the distributor node fetch data about all its distribution obligations from the query node and remove all the no-longer assigned data objects from local storage and cache state
+
+`cacheCleanup`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-intervals-properties-cachecleanup.md "undefined#/properties/intervals/properties/cacheCleanup")
+
+### cacheCleanup Type
+
+`integer`
+
+### cacheCleanup Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`

+ 3 - 0
distributor-node/docs/schema/definition-properties-keys-items.md

@@ -0,0 +1,3 @@
+## items Type
+
+`string`

+ 7 - 0
distributor-node/docs/schema/definition-properties-keys.md

@@ -0,0 +1,7 @@
+## keys Type
+
+`string[]`
+
+## keys Constraints
+
+**minimum number of items**: the minimum number of items for this array is: `1`

+ 7 - 0
distributor-node/docs/schema/definition-properties-limits-properties-maxconcurrentoutboundconnections.md

@@ -0,0 +1,7 @@
+## maxConcurrentOutboundConnections Type
+
+`integer`
+
+## maxConcurrentOutboundConnections Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`

+ 7 - 0
distributor-node/docs/schema/definition-properties-limits-properties-maxconcurrentstoragenodedownloads.md

@@ -0,0 +1,7 @@
+## maxConcurrentStorageNodeDownloads Type
+
+`integer`
+
+## maxConcurrentStorageNodeDownloads Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`

+ 7 - 0
distributor-node/docs/schema/definition-properties-limits-properties-outboundrequeststimeout.md

@@ -0,0 +1,7 @@
+## outboundRequestsTimeout Type
+
+`integer`
+
+## outboundRequestsTimeout Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`

+ 13 - 0
distributor-node/docs/schema/definition-properties-limits-properties-storage.md

@@ -0,0 +1,13 @@
+## storage Type
+
+`string`
+
+## storage Constraints
+
+**pattern**: the string must match the following regular expression: 
+
+```regexp
+^[0-9]+(B|K|M|G|T)$
+```
+
+[try pattern](https://regexr.com/?expression=%5E%5B0-9%5D%2B\(B%7CK%7CM%7CG%7CT\)%24 "try regular expression with regexr.com")

+ 106 - 0
distributor-node/docs/schema/definition-properties-limits.md

@@ -0,0 +1,106 @@
+## limits Type
+
+`object` ([Details](definition-properties-limits.md))
+
+# limits Properties
+
+| Property                                                                | Type      | Required | Nullable       | Defined by                                                                                                                                                                                 |
+| :---------------------------------------------------------------------- | :-------- | :------- | :------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [storage](#storage)                                                     | `string`  | Required | cannot be null | [Distributor node configuration](definition-properties-limits-properties-storage.md "undefined#/properties/limits/properties/storage")                                                     |
+| [maxConcurrentStorageNodeDownloads](#maxconcurrentstoragenodedownloads) | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-limits-properties-maxconcurrentstoragenodedownloads.md "undefined#/properties/limits/properties/maxConcurrentStorageNodeDownloads") |
+| [maxConcurrentOutboundConnections](#maxconcurrentoutboundconnections)   | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-limits-properties-maxconcurrentoutboundconnections.md "undefined#/properties/limits/properties/maxConcurrentOutboundConnections")   |
+| [outboundRequestsTimeout](#outboundrequeststimeout)                     | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-limits-properties-outboundrequeststimeout.md "undefined#/properties/limits/properties/outboundRequestsTimeout")                     |
+
+## storage
+
+Maximum total size of all (cached) assets stored in `directories.assets`
+
+`storage`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits-properties-storage.md "undefined#/properties/limits/properties/storage")
+
+### storage Type
+
+`string`
+
+### storage Constraints
+
+**pattern**: the string must match the following regular expression: 
+
+```regexp
+^[0-9]+(B|K|M|G|T)$
+```
+
+[try pattern](https://regexr.com/?expression=%5E%5B0-9%5D%2B\(B%7CK%7CM%7CG%7CT\)%24 "try regular expression with regexr.com")
+
+## maxConcurrentStorageNodeDownloads
+
+Maximum number of concurrent downloads from the storage node(s)
+
+`maxConcurrentStorageNodeDownloads`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits-properties-maxconcurrentstoragenodedownloads.md "undefined#/properties/limits/properties/maxConcurrentStorageNodeDownloads")
+
+### maxConcurrentStorageNodeDownloads Type
+
+`integer`
+
+### maxConcurrentStorageNodeDownloads Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`
+
+## maxConcurrentOutboundConnections
+
+Maximum number of total simultaneous outbound connections to storage node(s)
+
+`maxConcurrentOutboundConnections`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits-properties-maxconcurrentoutboundconnections.md "undefined#/properties/limits/properties/maxConcurrentOutboundConnections")
+
+### maxConcurrentOutboundConnections Type
+
+`integer`
+
+### maxConcurrentOutboundConnections Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`
+
+## outboundRequestsTimeout
+
+Timeout for all outbound storage node http requests in miliseconds
+
+`outboundRequestsTimeout`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits-properties-outboundrequeststimeout.md "undefined#/properties/limits/properties/outboundRequestsTimeout")
+
+### outboundRequestsTimeout Type
+
+`integer`
+
+### outboundRequestsTimeout Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`

+ 18 - 0
distributor-node/docs/schema/definition-properties-log-properties-console.md

@@ -0,0 +1,18 @@
+## console Type
+
+`string`
+
+## console Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"error"`   |             |
+| `"warn"`    |             |
+| `"info"`    |             |
+| `"http"`    |             |
+| `"verbose"` |             |
+| `"debug"`   |             |
+| `"silly"`   |             |
+| `"off"`     |             |

+ 18 - 0
distributor-node/docs/schema/definition-properties-log-properties-elastic.md

@@ -0,0 +1,18 @@
+## elastic Type
+
+`string`
+
+## elastic Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"error"`   |             |
+| `"warn"`    |             |
+| `"info"`    |             |
+| `"http"`    |             |
+| `"verbose"` |             |
+| `"debug"`   |             |
+| `"silly"`   |             |
+| `"off"`     |             |

+ 18 - 0
distributor-node/docs/schema/definition-properties-log-properties-file.md

@@ -0,0 +1,18 @@
+## file Type
+
+`string`
+
+## file Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"error"`   |             |
+| `"warn"`    |             |
+| `"info"`    |             |
+| `"http"`    |             |
+| `"verbose"` |             |
+| `"debug"`   |             |
+| `"silly"`   |             |
+| `"off"`     |             |

+ 110 - 0
distributor-node/docs/schema/definition-properties-log.md

@@ -0,0 +1,110 @@
+## log Type
+
+`object` ([Details](definition-properties-log.md))
+
+# log Properties
+
+| Property            | Type     | Required | Nullable       | Defined by                                                                                                                       |
+| :------------------ | :------- | :------- | :------------- | :------------------------------------------------------------------------------------------------------------------------------- |
+| [file](#file)       | `string` | Optional | cannot be null | [Distributor node configuration](definition-properties-log-properties-file.md "undefined#/properties/log/properties/file")       |
+| [console](#console) | `string` | Optional | cannot be null | [Distributor node configuration](definition-properties-log-properties-console.md "undefined#/properties/log/properties/console") |
+| [elastic](#elastic) | `string` | Optional | cannot be null | [Distributor node configuration](definition-properties-log-properties-elastic.md "undefined#/properties/log/properties/elastic") |
+
+## file
+
+Minimum level of logs written to a file specified in `directories.logs`
+
+`file`
+
+*   is optional
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-log-properties-file.md "undefined#/properties/log/properties/file")
+
+### file Type
+
+`string`
+
+### file Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"error"`   |             |
+| `"warn"`    |             |
+| `"info"`    |             |
+| `"http"`    |             |
+| `"verbose"` |             |
+| `"debug"`   |             |
+| `"silly"`   |             |
+| `"off"`     |             |
+
+## console
+
+Minimum level of logs outputted to a console
+
+`console`
+
+*   is optional
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-log-properties-console.md "undefined#/properties/log/properties/console")
+
+### console Type
+
+`string`
+
+### console Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"error"`   |             |
+| `"warn"`    |             |
+| `"info"`    |             |
+| `"http"`    |             |
+| `"verbose"` |             |
+| `"debug"`   |             |
+| `"silly"`   |             |
+| `"off"`     |             |
+
+## elastic
+
+Minimum level of logs sent to elasticsearch endpoint specified in `endpoints.elasticSearch`
+
+`elastic`
+
+*   is optional
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-log-properties-elastic.md "undefined#/properties/log/properties/elastic")
+
+### elastic Type
+
+`string`
+
+### elastic Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"error"`   |             |
+| `"warn"`    |             |
+| `"info"`    |             |
+| `"http"`    |             |
+| `"verbose"` |             |
+| `"debug"`   |             |
+| `"silly"`   |             |
+| `"off"`     |             |

+ 7 - 0
distributor-node/docs/schema/definition-properties-port.md

@@ -0,0 +1,7 @@
+## port Type
+
+`integer`
+
+## port Constraints
+
+**minimum**: the value of this number must greater than or equal to: `0`

+ 7 - 0
distributor-node/docs/schema/definition-properties-workerid.md

@@ -0,0 +1,7 @@
+## workerId Type
+
+`integer`
+
+## workerId Constraints
+
+**minimum**: the value of this number must greater than or equal to: `0`

+ 197 - 0
distributor-node/docs/schema/definition.md

@@ -0,0 +1,197 @@
+## Distributor node configuration Type
+
+`object` ([Distributor node configuration](definition.md))
+
+# Distributor node configuration Properties
+
+| Property                    | Type      | Required | Nullable       | Defined by                                                                                                 |
+| :-------------------------- | :-------- | :------- | :------------- | :--------------------------------------------------------------------------------------------------------- |
+| [endpoints](#endpoints)     | `object`  | Required | cannot be null | [Distributor node configuration](definition-properties-endpoints.md "undefined#/properties/endpoints")     |
+| [directories](#directories) | `object`  | Required | cannot be null | [Distributor node configuration](definition-properties-directories.md "undefined#/properties/directories") |
+| [log](#log)                 | `object`  | Optional | cannot be null | [Distributor node configuration](definition-properties-log.md "undefined#/properties/log")                 |
+| [limits](#limits)           | `object`  | Required | cannot be null | [Distributor node configuration](definition-properties-limits.md "undefined#/properties/limits")           |
+| [intervals](#intervals)     | `object`  | Required | cannot be null | [Distributor node configuration](definition-properties-intervals.md "undefined#/properties/intervals")     |
+| [port](#port)               | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-port.md "undefined#/properties/port")               |
+| [keys](#keys)               | `array`   | Required | cannot be null | [Distributor node configuration](definition-properties-keys.md "undefined#/properties/keys")               |
+| [buckets](#buckets)         | Merged    | Required | cannot be null | [Distributor node configuration](definition-properties-buckets.md "undefined#/properties/buckets")         |
+| [workerId](#workerid)       | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-workerid.md "undefined#/properties/workerId")       |
+
+## endpoints
+
+Specifies external endpoints that the distributor node will connect to
+
+`endpoints`
+
+*   is required
+
+*   Type: `object` ([Details](definition-properties-endpoints.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-endpoints.md "undefined#/properties/endpoints")
+
+### endpoints Type
+
+`object` ([Details](definition-properties-endpoints.md))
+
+## directories
+
+Specifies paths where node's data will be stored
+
+`directories`
+
+*   is required
+
+*   Type: `object` ([Details](definition-properties-directories.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-directories.md "undefined#/properties/directories")
+
+### directories Type
+
+`object` ([Details](definition-properties-directories.md))
+
+## log
+
+Specifies minimum log levels by supported log outputs
+
+`log`
+
+*   is optional
+
+*   Type: `object` ([Details](definition-properties-log.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-log.md "undefined#/properties/log")
+
+### log Type
+
+`object` ([Details](definition-properties-log.md))
+
+## limits
+
+Specifies node limits w\.r.t. storage, outbound connections etc.
+
+`limits`
+
+*   is required
+
+*   Type: `object` ([Details](definition-properties-limits.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits.md "undefined#/properties/limits")
+
+### limits Type
+
+`object` ([Details](definition-properties-limits.md))
+
+## intervals
+
+Specifies how often periodic tasks (for example cache cleanup) are executed by the node.
+
+`intervals`
+
+*   is required
+
+*   Type: `object` ([Details](definition-properties-intervals.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-intervals.md "undefined#/properties/intervals")
+
+### intervals Type
+
+`object` ([Details](definition-properties-intervals.md))
+
+## port
+
+Distributor node http server port
+
+`port`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-port.md "undefined#/properties/port")
+
+### port Type
+
+`integer`
+
+### port Constraints
+
+**minimum**: the value of this number must greater than or equal to: `0`
+
+## keys
+
+Specifies the keys to use within distributor node CLI. Must be provided in form of substrate uris (ie.: //Alice)
+
+`keys`
+
+*   is required
+
+*   Type: `string[]`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-keys.md "undefined#/properties/keys")
+
+### keys Type
+
+`string[]`
+
+### keys Constraints
+
+**minimum number of items**: the minimum number of items for this array is: `1`
+
+## buckets
+
+Specifies the buckets distributed by the node
+
+`buckets`
+
+*   is required
+
+*   Type: merged type ([Details](definition-properties-buckets.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-buckets.md "undefined#/properties/buckets")
+
+### buckets Type
+
+merged type ([Details](definition-properties-buckets.md))
+
+one (and only one) of
+
+*   [Untitled array in Distributor node configuration](definition-properties-buckets-oneof-0.md "check type definition")
+
+*   [Untitled string in Distributor node configuration](definition-properties-buckets-oneof-1.md "check type definition")
+
+## workerId
+
+ID of the node operator (distribution working group worker)
+
+`workerId`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-workerid.md "undefined#/properties/workerId")
+
+### workerId Type
+
+`integer`
+
+### workerId Constraints
+
+**minimum**: the value of this number must greater than or equal to: `0`

+ 9 - 4
distributor-node/package.json

@@ -68,7 +68,9 @@
     "nyc": "^14",
     "openapi-typescript": "^4.0.2",
     "ts-node": "^8",
-    "typescript": "^3.3"
+    "typescript": "^3.3",
+    "@adobe/jsonschema2md": "https://github.com/adobe/jsonschema2md",
+    "widdershins": "^4.0.1"
   },
   "engines": {
     "node": ">=14.16.1"
@@ -99,16 +101,19 @@
   },
   "scripts": {
     "postpack": "rm -f oclif.manifest.json",
-    "prepack": "rm -rf lib && tsc -b && oclif-dev manifest && oclif-dev readme",
+    "prepack": "rm -rf lib && tsc -b && oclif-dev manifest && generate:all",
     "test": "nyc --extension .ts mocha --forbid-only \"test/**/*.test.ts\"",
-    "version": "oclif-dev readme && git add README.md",
-    "generate:types:json-schema": "yarn ts-node ./src/services/validation/generateTypes.ts",
+    "version": "generate:docs:cli && git add docs/cli/*",
+    "generate:types:json-schema": "yarn ts-node ./src/schemas/scripts/generateTypes.ts",
     "generate:types:graphql": "yarn graphql-codegen -c ./src/services/networking/query-node/codegen.yml",
     "generate:types:openapi": "yarn openapi-typescript ./src/api-spec/openapi.yml -o ./src/types/generated/OpenApi.ts -c ../prettierrc.js",
     "generate:types:all": "yarn generate:types:json-schema && yarn generate:types:graphql && yarn generate:types:openapi",
     "generate:api:storage-node": "yarn openapi-generator-cli generate -i ../storage-node-v2/src/api-spec/openapi.yaml -g typescript-axios -o ./src/services/networking/storage-node/generated",
     "generate:api:distributor-node": "yarn openapi-generator-cli generate -i ./src/api-spec/openapi.yml -g typescript-axios -o ./src/services/networking/distributor-node/generated",
     "generate:api:all": "yarn generate:api:storage-node && yarn generate:api:distributor-node",
+    "generate:docs:cli": "yarn oclif-dev readme --multi --dir ./docs/commands",
+    "generate:docs:config": "yarn ts-node --transpile-only ./src/schemas/scripts/generateConfigDoc.ts",
+    "generate:docs:api": "yarn widdershins ./src/api-spec/openapi.yml --language_tabs javascript:JavaScript shell:Shell -o ./docs/api/index.md -u ./docs/api/templates",
     "generate:all": "yarn generate:types:all && yarn generate:api:all",
     "build": "rm -rf lib && tsc --build tsconfig.json && cp -r ./src/api-spec ./lib/api-spec",
     "lint": "eslint ./src --ext .ts",

+ 2 - 2
distributor-node/src/api-spec/openapi.yml

@@ -56,7 +56,7 @@ paths:
       tags:
         - public
       parameters:
-        - $ref: '#components/parameters/ObjectId'
+        - $ref: '#/components/parameters/ObjectId'
       responses:
         200:
           description: Object is supported and should be send on GET request.
@@ -75,7 +75,7 @@ paths:
       tags:
         - public
       parameters:
-        - $ref: '#components/parameters/ObjectId'
+        - $ref: '#/components/parameters/ObjectId'
       responses:
         200:
           description: Full available object data sent

+ 171 - 0
distributor-node/src/schemas/configSchema.ts

@@ -0,0 +1,171 @@
+import { JSONSchema4 } from 'json-schema'
+import winston from 'winston'
+import { MAX_CONCURRENT_RESPONSE_TIME_CHECKS } from '../services/networking/NetworkingService'
+
+export const bytesizeUnits = ['B', 'K', 'M', 'G', 'T']
+export const bytesizeRegex = new RegExp(`^[0-9]+(${bytesizeUnits.join('|')})$`)
+
+export const configSchema: JSONSchema4 = {
+  title: 'Distributor node configuration',
+  description: 'Configuration schema for distirubtor CLI and node',
+  type: 'object',
+  required: ['endpoints', 'directories', 'buckets', 'keys', 'port', 'workerId', 'limits', 'intervals'],
+  additionalProperties: false,
+  properties: {
+    endpoints: {
+      type: 'object',
+      description: 'Specifies external endpoints that the distributor node will connect to',
+      additionalProperties: false,
+      required: ['queryNode', 'substrateNode'],
+      properties: {
+        queryNode: {
+          description: 'Query node graphql server uri (for example: http://localhost:8081/graphql)',
+          type: 'string',
+        },
+        joystreamNodeWs: {
+          description: 'Joystream node websocket api uri (for example: ws://localhost:9944)',
+          type: 'string',
+        },
+        elasticSearch: {
+          description: 'Elasticsearch uri used for submitting the distributor node logs (if enabled via `log.elastic`)',
+          type: 'string',
+        },
+      },
+    },
+    directories: {
+      type: 'object',
+      required: ['assets', 'state'],
+      additionalProperties: false,
+      description: "Specifies paths where node's data will be stored",
+      assets: {
+        description: 'Path to a directory where all the cached assets will be stored',
+        type: 'string',
+      },
+      cacheState: {
+        description:
+          'Path to a directory where information about the current cache state will be stored (LRU-SP cache data, stored assets mime types etc.)',
+        type: 'string',
+      },
+      logs: {
+        description: 'Path to a directory where logs will be stored if logging to a file was enabled (via `log.file`).',
+        type: 'string',
+      },
+    },
+    log: {
+      type: 'object',
+      additionalProperties: false,
+      description: 'Specifies minimum log levels by supported log outputs',
+      properties: {
+        file: {
+          description: 'Minimum level of logs written to a file specified in `directories.logs`',
+          type: 'string',
+          enum: [...Object.keys(winston.config.npm.levels), 'off'],
+        },
+        console: {
+          description: 'Minimum level of logs outputted to a console',
+          type: 'string',
+          enum: [...Object.keys(winston.config.npm.levels), 'off'],
+        },
+        elastic: {
+          description: 'Minimum level of logs sent to elasticsearch endpoint specified in `endpoints.elasticSearch`',
+          type: 'string',
+          enum: [...Object.keys(winston.config.npm.levels), 'off'],
+        },
+      },
+    },
+    limits: {
+      type: 'object',
+      required: [
+        'storage',
+        'maxConcurrentStorageNodeDownloads',
+        'maxConcurrentOutboundConnections',
+        'outboundRequestsTimeout',
+      ],
+      description: 'Specifies node limits w.r.t. storage, outbound connections etc.',
+      additionalProperties: false,
+      properties: {
+        storage: {
+          description: 'Maximum total size of all (cached) assets stored in `directories.assets`',
+          type: 'string',
+          pattern: bytesizeRegex.source,
+        },
+        maxConcurrentStorageNodeDownloads: {
+          description: 'Maximum number of concurrent downloads from the storage node(s)',
+          type: 'integer',
+          minimum: 1,
+        },
+        maxConcurrentOutboundConnections: {
+          description: 'Maximum number of total simultaneous outbound connections to storage node(s)',
+          type: 'integer',
+          minimum: 1,
+        },
+        outboundRequestsTimeout: {
+          description: 'Timeout for all outbound storage node http requests in miliseconds',
+          type: 'integer',
+          minimum: 1,
+        },
+      },
+    },
+    intervals: {
+      type: 'object',
+      required: ['saveCacheState', 'checkStorageNodeResponseTimes', 'cacheCleanup'],
+      additionalProperties: false,
+      description: 'Specifies how often periodic tasks (for example cache cleanup) are executed by the node.',
+      properties: {
+        saveCacheState: {
+          description:
+            'How often, in seconds, will the cache state be saved in `directories.state`. ' +
+            'Independently of the specified interval, the node will always try to save cache state before exiting.',
+          type: 'integer',
+          minimum: 1,
+        },
+        checkStorageNodeResponseTimes: {
+          description:
+            'How often, in seconds, will the distributor node attempt to send requests to all current storage node endpoints ' +
+            'in order to check how quickly they respond. ' +
+            `The node will never make more than ${MAX_CONCURRENT_RESPONSE_TIME_CHECKS} such requests concurrently.`,
+          type: 'integer',
+          minimum: 1,
+        },
+        cacheCleanup: {
+          description:
+            'How often, in seconds, will the distributor node fetch data about all its distribution obligations from the query node ' +
+            'and remove all the no-longer assigned data objects from local storage and cache state',
+          type: 'integer',
+          minimum: 1,
+        },
+      },
+    },
+    port: { description: 'Distributor node http server port', type: 'integer', minimum: 0 },
+    keys: {
+      description:
+        'Specifies the keys to use within distributor node CLI. Must be provided in form of substrate uris (ie.: //Alice)',
+      type: 'array',
+      items: { type: 'string' },
+      minItems: 1,
+    },
+    buckets: {
+      description: 'Specifies the buckets distributed by the node',
+      oneOf: [
+        {
+          description: 'List of distribution bucket ids',
+          type: 'array',
+          items: { type: 'integer', minimum: 0 },
+          minItems: 1,
+        },
+        {
+          description: 'Distribute all buckets assigned to worker specified in `workerId`',
+          type: 'string',
+          enum: ['all'],
+        },
+      ],
+    },
+    workerId: {
+      description: 'ID of the node operator (distribution working group worker)',
+      type: 'integer',
+      minimum: 0,
+    },
+  },
+}
+
+export default configSchema

+ 0 - 0
distributor-node/src/services/validation/schemas/familyMetadataSchema.ts → distributor-node/src/schemas/familyMetadataSchema.ts


+ 3 - 3
distributor-node/src/services/validation/schemas/index.ts → distributor-node/src/schemas/index.ts

@@ -1,6 +1,6 @@
-import { ConfigJson } from '../../../types/generated/ConfigJson'
-import { OperatorMetadataJson } from '../../../types/generated/OperatorMetadataJson'
-import { FamilyMetadataJson } from '../../../types/generated/FamilyMetadataJson'
+import { ConfigJson } from '../types/generated/ConfigJson'
+import { OperatorMetadataJson } from '../types/generated/OperatorMetadataJson'
+import { FamilyMetadataJson } from '../types/generated/FamilyMetadataJson'
 import { configSchema } from './configSchema'
 import { familyMetadataSchema } from './familyMetadataSchema'
 import { operatorMetadataSchema } from './operatorMetadataSchema'

+ 0 - 0
distributor-node/src/services/validation/schemas/operatorMetadataSchema.ts → distributor-node/src/schemas/operatorMetadataSchema.ts


+ 8 - 0
distributor-node/src/schemas/scripts/generateConfigDoc.ts

@@ -0,0 +1,8 @@
+import { jsonschema2md } from '@adobe/jsonschema2md'
+import { configSchema } from '../configSchema'
+import path from 'path'
+
+console.log(configSchema)
+jsonschema2md(configSchema, {
+  outDir: path.resolve(__dirname, `../../../docs/schema`),
+})

+ 1 - 1
distributor-node/src/services/validation/generateTypes.ts → distributor-node/src/schemas/scripts/generateTypes.ts

@@ -1,7 +1,7 @@
 import fs from 'fs'
 import path from 'path'
 import { compile } from 'json-schema-to-typescript'
-import { schemas } from './schemas'
+import { schemas } from '..'
 
 // eslint-disable-next-line @typescript-eslint/no-var-requires
 const prettierConfig = require('@joystream/prettier-config')

+ 2 - 2
distributor-node/src/services/networking/NetworkingService.ts

@@ -21,8 +21,8 @@ import https from 'https'
 import { parseAxiosError } from '../parsers/errors'
 
 // Concurrency limits
-const MAX_CONCURRENT_AVAILABILITY_CHECKS_PER_DOWNLOAD = 10
-const MAX_CONCURRENT_RESPONSE_TIME_CHECKS = 10
+export const MAX_CONCURRENT_AVAILABILITY_CHECKS_PER_DOWNLOAD = 10
+export const MAX_CONCURRENT_RESPONSE_TIME_CHECKS = 10
 
 export class NetworkingService {
   private config: ReadonlyConfig

+ 30 - 16
distributor-node/src/services/networking/distributor-node/generated/api.ts

@@ -124,11 +124,15 @@ export const PublicApiAxiosParamCreator = function (configuration?: Configuratio
     return {
         /**
          * Returns a media file.
+         * @param {string} objectId Data Object ID
          * @param {*} [options] Override http request option.
          * @throws {RequiredError}
          */
-        publicAsset: async (options: any = {}): Promise<RequestArgs> => {
-            const localVarPath = `/asset/{objectId}`;
+        publicAsset: async (objectId: string, options: any = {}): Promise<RequestArgs> => {
+            // verify required parameter 'objectId' is not null or undefined
+            assertParamExists('publicAsset', 'objectId', objectId)
+            const localVarPath = `/asset/{objectId}`
+                .replace(`{${"objectId"}}`, encodeURIComponent(String(objectId)));
             // use dummy base URL string because the URL constructor only accepts absolute URLs.
             const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
             let baseOptions;
@@ -153,11 +157,15 @@ export const PublicApiAxiosParamCreator = function (configuration?: Configuratio
         },
         /**
          * Returns asset response headers (cache status, content type and/or length, accepted ranges etc.)
+         * @param {string} objectId Data Object ID
          * @param {*} [options] Override http request option.
          * @throws {RequiredError}
          */
-        publicAssetHead: async (options: any = {}): Promise<RequestArgs> => {
-            const localVarPath = `/asset/{objectId}`;
+        publicAssetHead: async (objectId: string, options: any = {}): Promise<RequestArgs> => {
+            // verify required parameter 'objectId' is not null or undefined
+            assertParamExists('publicAssetHead', 'objectId', objectId)
+            const localVarPath = `/asset/{objectId}`
+                .replace(`{${"objectId"}}`, encodeURIComponent(String(objectId)));
             // use dummy base URL string because the URL constructor only accepts absolute URLs.
             const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
             let baseOptions;
@@ -250,20 +258,22 @@ export const PublicApiFp = function(configuration?: Configuration) {
     return {
         /**
          * Returns a media file.
+         * @param {string} objectId Data Object ID
          * @param {*} [options] Override http request option.
          * @throws {RequiredError}
          */
-        async publicAsset(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> {
-            const localVarAxiosArgs = await localVarAxiosParamCreator.publicAsset(options);
+        async publicAsset(objectId: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> {
+            const localVarAxiosArgs = await localVarAxiosParamCreator.publicAsset(objectId, options);
             return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
         },
         /**
          * Returns asset response headers (cache status, content type and/or length, accepted ranges etc.)
+         * @param {string} objectId Data Object ID
          * @param {*} [options] Override http request option.
          * @throws {RequiredError}
          */
-        async publicAssetHead(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
-            const localVarAxiosArgs = await localVarAxiosParamCreator.publicAssetHead(options);
+        async publicAssetHead(objectId: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
+            const localVarAxiosArgs = await localVarAxiosParamCreator.publicAssetHead(objectId, options);
             return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
         },
         /**
@@ -296,19 +306,21 @@ export const PublicApiFactory = function (configuration?: Configuration, basePat
     return {
         /**
          * Returns a media file.
+         * @param {string} objectId Data Object ID
          * @param {*} [options] Override http request option.
          * @throws {RequiredError}
          */
-        publicAsset(options?: any): AxiosPromise<any> {
-            return localVarFp.publicAsset(options).then((request) => request(axios, basePath));
+        publicAsset(objectId: string, options?: any): AxiosPromise<any> {
+            return localVarFp.publicAsset(objectId, options).then((request) => request(axios, basePath));
         },
         /**
          * Returns asset response headers (cache status, content type and/or length, accepted ranges etc.)
+         * @param {string} objectId Data Object ID
          * @param {*} [options] Override http request option.
          * @throws {RequiredError}
          */
-        publicAssetHead(options?: any): AxiosPromise<void> {
-            return localVarFp.publicAssetHead(options).then((request) => request(axios, basePath));
+        publicAssetHead(objectId: string, options?: any): AxiosPromise<void> {
+            return localVarFp.publicAssetHead(objectId, options).then((request) => request(axios, basePath));
         },
         /**
          * Returns list of distributed buckets
@@ -338,22 +350,24 @@ export const PublicApiFactory = function (configuration?: Configuration, basePat
 export class PublicApi extends BaseAPI {
     /**
      * Returns a media file.
+     * @param {string} objectId Data Object ID
      * @param {*} [options] Override http request option.
      * @throws {RequiredError}
      * @memberof PublicApi
      */
-    public publicAsset(options?: any) {
-        return PublicApiFp(this.configuration).publicAsset(options).then((request) => request(this.axios, this.basePath));
+    public publicAsset(objectId: string, options?: any) {
+        return PublicApiFp(this.configuration).publicAsset(objectId, options).then((request) => request(this.axios, this.basePath));
     }
 
     /**
      * Returns asset response headers (cache status, content type and/or length, accepted ranges etc.)
+     * @param {string} objectId Data Object ID
      * @param {*} [options] Override http request option.
      * @throws {RequiredError}
      * @memberof PublicApi
      */
-    public publicAssetHead(options?: any) {
-        return PublicApiFp(this.configuration).publicAssetHead(options).then((request) => request(this.axios, this.basePath));
+    public publicAssetHead(objectId: string, options?: any) {
+        return PublicApiFp(this.configuration).publicAssetHead(objectId, options).then((request) => request(this.axios, this.basePath));
     }
 
     /**

File diff suppressed because it is too large
+ 175 - 641
distributor-node/src/services/networking/query-node/generated/schema.ts


+ 1 - 1
distributor-node/src/services/parsers/ConfigParserService.ts

@@ -4,7 +4,7 @@ import fs from 'fs'
 import path from 'path'
 import YAML from 'yaml'
 import _ from 'lodash'
-import configSchema, { bytesizeUnits } from '../validation/schemas/configSchema'
+import configSchema, { bytesizeUnits } from '../../schemas/configSchema'
 import { JSONSchema4 } from 'json-schema'
 
 const MIN_CACHE_SIZE = 20 * Math.pow(1024, 3)

+ 11 - 10
distributor-node/src/services/server/controllers/public.ts

@@ -94,13 +94,14 @@ export class PublicApiController {
 
     // Handle request using pending download file if this makes sense in current context:
     if (this.content.exists(objectId)) {
+      const partiallyDownloadedContentSize = this.content.fileSize(objectId)
       const range = req.range(objectSize)
       if (!range || range === -1 || range === -2 || range.length !== 1 || range.type !== 'bytes') {
         // Range is not provided / invalid - serve data from pending download file
         return this.servePendingDownloadAssetFromFile(req, res, next, objectId, objectSize)
-      } else if (range[0].start === 0) {
-        // Range starts from the beginning of the content - serve data from pending download file
-        return this.servePendingDownloadAssetFromFile(req, res, next, objectId, objectSize, range[0].end)
+      } else if (range[0].start <= partiallyDownloadedContentSize) {
+        // Range starts at the already downloaded part of the content - serve data from pending download file
+        return this.servePendingDownloadAssetFromFile(req, res, next, objectId, objectSize, range[0])
       }
     }
 
@@ -116,19 +117,19 @@ export class PublicApiController {
     next: express.NextFunction,
     objectId: string,
     objectSize: number,
-    rangeEnd?: number
+    range?: { start: number; end: number }
   ) {
-    const isRange = rangeEnd !== undefined
-    this.logger.verbose(`Serving pending download asset from file`, { objectId, isRange, objectSize, rangeEnd })
+    this.logger.verbose(`Serving pending download asset from file`, { objectId, objectSize, range })
     const stream = this.content.createContinousReadStream(objectId, {
-      end: isRange ? rangeEnd || 0 : objectSize - 1,
+      start: range?.start,
+      end: range !== undefined ? range.end : objectSize - 1,
     })
-    res.status(isRange ? 206 : 200)
+    res.status(range !== undefined ? 206 : 200)
     res.setHeader('accept-ranges', 'bytes')
     res.setHeader('x-data-source', 'local')
     res.setHeader('content-disposition', 'inline')
-    if (isRange) {
-      res.setHeader('content-range', `bytes 0-${rangeEnd}/${objectSize}`)
+    if (range !== undefined) {
+      res.setHeader('content-range', `bytes ${range.start}-${range.end}/${objectSize}`)
     }
     stream.pipe(res)
     req.on('close', () => {

+ 1 - 1
distributor-node/src/services/validation/ValidationService.ts

@@ -1,5 +1,5 @@
 import Ajv from 'ajv'
-import { SchemaKey, schemas, TypeBySchemaKey } from './schemas'
+import { SchemaKey, schemas, TypeBySchemaKey } from '../../schemas'
 
 class ValidationError extends Error {
   public readonly errors: string[]

+ 0 - 61
distributor-node/src/services/validation/schemas/configSchema.ts

@@ -1,61 +0,0 @@
-import { JSONSchema4 } from 'json-schema'
-import { strictObject } from './utils'
-import winston from 'winston'
-
-export const bytesizeUnits = ['B', 'K', 'M', 'G', 'T']
-export const bytesizeRegex = new RegExp(`^[0-9]+(${bytesizeUnits.join('|')})$`)
-
-export const configSchema: JSONSchema4 = {
-  type: 'object',
-  required: ['id', 'endpoints', 'directories', 'buckets', 'keys', 'port', 'workerId', 'limits', 'intervals'],
-  additionalProperties: false,
-  properties: {
-    id: { type: 'string' },
-    endpoints: {
-      type: 'object',
-      additionalProperties: false,
-      required: ['queryNode', 'substrateNode'],
-      properties: {
-        queryNode: { type: 'string' },
-        substrateNode: { type: 'string' },
-        elasticSearch: { type: 'string' },
-      },
-    },
-    directories: strictObject({
-      data: { type: 'string' },
-      cache: { type: 'string' },
-      logs: { type: 'string' },
-    }),
-    log: {
-      type: 'object',
-      additionalProperties: false,
-      properties: {
-        file: { type: 'string', enum: [...Object.keys(winston.config.npm.levels), 'off'] },
-        console: { type: 'string', enum: [...Object.keys(winston.config.npm.levels), 'off'] },
-        elastic: { type: 'string', enum: [...Object.keys(winston.config.npm.levels), 'off'] },
-      },
-    },
-    limits: strictObject({
-      storage: { type: 'string', pattern: bytesizeRegex.source },
-      maxConcurrentStorageNodeDownloads: { type: 'integer', minimum: 1 },
-      maxConcurrentOutboundConnections: { type: 'integer', minimum: 1 },
-      outboundRequestsTimeout: { type: 'integer', minimum: 1 },
-    }),
-    intervals: strictObject({
-      saveCacheState: { type: 'integer', minimum: 1 },
-      checkStorageNodeResponseTimes: { type: 'integer', minimum: 1 },
-      cacheCleanup: { type: 'integer', minimum: 1 },
-    }),
-    port: { type: 'integer', minimum: 0 },
-    keys: { type: 'array', items: { type: 'string' }, minItems: 1 },
-    buckets: {
-      oneOf: [
-        { type: 'array', items: { type: 'integer', minimum: 0 }, minItems: 1 },
-        { type: 'string', enum: ['all'] },
-      ],
-    },
-    workerId: { type: 'integer', minimum: 0 },
-  },
-}
-
-export default configSchema

+ 0 - 10
distributor-node/src/services/validation/schemas/utils.ts

@@ -1,10 +0,0 @@
-import { JSONSchema4 } from 'json-schema'
-
-export function strictObject(properties: Exclude<JSONSchema4['properties'], undefined>): JSONSchema4 {
-  return {
-    type: 'object',
-    additionalProperties: false,
-    required: Object.keys(properties),
-    properties,
-  }
-}

+ 72 - 8
distributor-node/src/types/generated/ConfigJson.d.ts

@@ -5,36 +5,100 @@
  * and run json-schema-to-typescript to regenerate this file.
  */
 
-export interface ConfigJson {
-  id: string
+/**
+ * Configuration schema for distirubtor CLI and node
+ */
+export interface DistributorNodeConfiguration {
+  /**
+   * Specifies external endpoints that the distributor node will connect to
+   */
   endpoints: {
+    /**
+     * Query node graphql server uri (for example: http://localhost:8081/graphql)
+     */
     queryNode: string
-    substrateNode: string
+    /**
+     * Joystream node websocket api uri (for example: ws://localhost:9944)
+     */
+    joystreamNodeWs?: string
+    /**
+     * Elasticsearch uri used for submitting the distributor node logs (if enabled via `log.elastic`)
+     */
     elasticSearch?: string
   }
-  directories: {
-    data: string
-    cache: string
-    logs: string
-  }
+  /**
+   * Specifies paths where node's data will be stored
+   */
+  directories: {}
+  /**
+   * Specifies minimum log levels by supported log outputs
+   */
   log?: {
+    /**
+     * Minimum level of logs written to a file specified in `directories.logs`
+     */
     file?: 'error' | 'warn' | 'info' | 'http' | 'verbose' | 'debug' | 'silly' | 'off'
+    /**
+     * Minimum level of logs outputted to a console
+     */
     console?: 'error' | 'warn' | 'info' | 'http' | 'verbose' | 'debug' | 'silly' | 'off'
+    /**
+     * Minimum level of logs sent to elasticsearch endpoint specified in `endpoints.elasticSearch`
+     */
     elastic?: 'error' | 'warn' | 'info' | 'http' | 'verbose' | 'debug' | 'silly' | 'off'
   }
+  /**
+   * Specifies node limits w.r.t. storage, outbound connections etc.
+   */
   limits: {
+    /**
+     * Maximum total size of all (cached) assets stored in `directories.assets`
+     */
     storage: string
+    /**
+     * Maximum number of concurrent downloads from the storage node(s)
+     */
     maxConcurrentStorageNodeDownloads: number
+    /**
+     * Maximum number of total simultaneous outbound connections to storage node(s)
+     */
     maxConcurrentOutboundConnections: number
+    /**
+     * Timeout for all outbound storage node http requests in miliseconds
+     */
     outboundRequestsTimeout: number
   }
+  /**
+   * Specifies how often periodic tasks (for example cache cleanup) are executed by the node.
+   */
   intervals: {
+    /**
+     * How often, in seconds, will the cache state be saved in `directories.state`. Independently of the specified interval, the node will always try to save cache state before exiting.
+     */
     saveCacheState: number
+    /**
+     * How often, in seconds, will the distributor node attempt to send requests to all current storage node endpoints in order to check how quickly they respond. The node will never make more than 10 such requests concurrently.
+     */
     checkStorageNodeResponseTimes: number
+    /**
+     * How often, in seconds, will the distributor node fetch data about all its distribution obligations from the query node and remove all the no-longer assigned data objects from local storage and cache state
+     */
     cacheCleanup: number
   }
+  /**
+   * Distributor node http server port
+   */
   port: number
+  /**
+   * Specifies the keys to use within distributor node CLI. Must be provided in form of substrate uris (ie.: //Alice)
+   */
   keys: [string, ...string[]]
+  /**
+   * Specifies the buckets distributed by the node
+   */
   buckets: [number, ...number[]] | 'all'
+  /**
+   * ID of the node operator (distribution working group worker)
+   */
   workerId: number
 }

File diff suppressed because it is too large
+ 518 - 20
yarn.lock


Some files were not shown because too many files changed in this diff