Browse Source

Merge pull request #2582 from Lezek123/distributor-node

Distributor node
shamil-gadelshin 3 years ago
parent
commit
e33f59cc75
100 changed files with 5294 additions and 1 deletions
  1. 2 1
      devops/vscode/settings.json
  2. 28 0
      distributor-node.Dockerfile
  3. 2 0
      distributor-node/.eslintignore
  4. 15 0
      distributor-node/.eslintrc.js
  5. 9 0
      distributor-node/.gitignore
  6. 4 0
      distributor-node/.prettierignore
  7. 40 0
      distributor-node/README.md
  8. 3 0
      distributor-node/bin/run
  9. 3 0
      distributor-node/bin/run.cmd
  10. 40 0
      distributor-node/config.yml
  11. 25 0
      distributor-node/config/docker/config.docker.yml
  12. 5 0
      distributor-node/config/docker/filebeat.Dockerfile
  13. 19 0
      distributor-node/config/docker/filebeat.docker.yml
  14. 76 0
      distributor-node/docker-compose.yml
  15. 375 0
      distributor-node/docs/api/operator/index.md
  16. 382 0
      distributor-node/docs/api/public/index.md
  17. 142 0
      distributor-node/docs/api/templates/main.dot
  18. 46 0
      distributor-node/docs/commands/dev.md
  19. 23 0
      distributor-node/docs/commands/help.md
  20. 5 0
      distributor-node/docs/commands/index.md
  21. 322 0
      distributor-node/docs/commands/leader.md
  22. 126 0
      distributor-node/docs/commands/node.md
  23. 59 0
      distributor-node/docs/commands/operator.md
  24. 23 0
      distributor-node/docs/commands/start.md
  25. 415 0
      distributor-node/docs/node/index.md
  26. 3 0
      distributor-node/docs/schema/definition-properties-directories-properties-assets.md
  27. 3 0
      distributor-node/docs/schema/definition-properties-directories-properties-cachestate.md
  28. 46 0
      distributor-node/docs/schema/definition-properties-directories.md
  29. 13 0
      distributor-node/docs/schema/definition-properties-distributed-buckets-ids-items.md
  30. 9 0
      distributor-node/docs/schema/definition-properties-distributed-buckets-ids.md
  31. 3 0
      distributor-node/docs/schema/definition-properties-endpoints-properties-joystreamnodews.md
  32. 3 0
      distributor-node/docs/schema/definition-properties-endpoints-properties-querynode.md
  33. 46 0
      distributor-node/docs/schema/definition-properties-endpoints.md
  34. 7 0
      distributor-node/docs/schema/definition-properties-id.md
  35. 7 0
      distributor-node/docs/schema/definition-properties-intervals-properties-cachecleanup.md
  36. 7 0
      distributor-node/docs/schema/definition-properties-intervals-properties-checkstoragenoderesponsetimes.md
  37. 7 0
      distributor-node/docs/schema/definition-properties-intervals-properties-savecachestate.md
  38. 77 0
      distributor-node/docs/schema/definition-properties-intervals.md
  39. 3 0
      distributor-node/docs/schema/definition-properties-keys-items-oneof-json-backup-file-properties-keyfile.md
  40. 27 0
      distributor-node/docs/schema/definition-properties-keys-items-oneof-json-backup-file.md
  41. 3 0
      distributor-node/docs/schema/definition-properties-keys-items-oneof-mnemonic-phrase-properties-mnemonic.md
  42. 21 0
      distributor-node/docs/schema/definition-properties-keys-items-oneof-mnemonic-phrase-properties-type.md
  43. 64 0
      distributor-node/docs/schema/definition-properties-keys-items-oneof-mnemonic-phrase.md
  44. 3 0
      distributor-node/docs/schema/definition-properties-keys-items-oneof-substrate-uri-properties-suri.md
  45. 21 0
      distributor-node/docs/schema/definition-properties-keys-items-oneof-substrate-uri-properties-type.md
  46. 64 0
      distributor-node/docs/schema/definition-properties-keys-items-oneof-substrate-uri.md
  47. 11 0
      distributor-node/docs/schema/definition-properties-keys-items.md
  48. 7 0
      distributor-node/docs/schema/definition-properties-keys.md
  49. 15 0
      distributor-node/docs/schema/definition-properties-limits-properties-dataobjectsourcebyobjectidttl.md
  50. 13 0
      distributor-node/docs/schema/definition-properties-limits-properties-maxcacheditemsize.md
  51. 7 0
      distributor-node/docs/schema/definition-properties-limits-properties-maxconcurrentoutboundconnections.md
  52. 7 0
      distributor-node/docs/schema/definition-properties-limits-properties-maxconcurrentstoragenodedownloads.md
  53. 7 0
      distributor-node/docs/schema/definition-properties-limits-properties-outboundrequeststimeoutms.md
  54. 7 0
      distributor-node/docs/schema/definition-properties-limits-properties-pendingdownloadtimeoutsec.md
  55. 13 0
      distributor-node/docs/schema/definition-properties-limits-properties-storage.md
  56. 189 0
      distributor-node/docs/schema/definition-properties-limits.md
  57. 41 0
      distributor-node/docs/schema/definition-properties-logs-properties-console-logging-options.md
  58. 3 0
      distributor-node/docs/schema/definition-properties-logs-properties-elasticsearch-logging-options-properties-endpoint.md
  59. 60 0
      distributor-node/docs/schema/definition-properties-logs-properties-elasticsearch-logging-options.md
  60. 3 0
      distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-archive.md
  61. 22 0
      distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-frequency.md
  62. 17 0
      distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-level.md
  63. 7 0
      distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-maxfiles.md
  64. 7 0
      distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-maxsize.md
  65. 3 0
      distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-path.md
  66. 163 0
      distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options.md
  67. 65 0
      distributor-node/docs/schema/definition-properties-logs.md
  68. 3 0
      distributor-node/docs/schema/definition-properties-operatorapi-properties-hmacsecret.md
  69. 7 0
      distributor-node/docs/schema/definition-properties-operatorapi-properties-port.md
  70. 50 0
      distributor-node/docs/schema/definition-properties-operatorapi.md
  71. 7 0
      distributor-node/docs/schema/definition-properties-publicapi-properties-port.md
  72. 31 0
      distributor-node/docs/schema/definition-properties-publicapi.md
  73. 7 0
      distributor-node/docs/schema/definition-properties-workerid.md
  74. 235 0
      distributor-node/docs/schema/definition.md
  75. 7 0
      distributor-node/openapitools.json
  76. 153 0
      distributor-node/package.json
  77. 15 0
      distributor-node/scripts/data/family-metadata.json
  78. 12 0
      distributor-node/scripts/data/operator-metadata.json
  79. 21 0
      distributor-node/scripts/init-bucket.sh
  80. 57 0
      distributor-node/scripts/test-commands.sh
  81. 1 0
      distributor-node/src/@types/@elastic/esc-winston-format/index.d.ts
  82. 1 0
      distributor-node/src/@types/js-image-generator/index.d.ts
  83. 119 0
      distributor-node/src/api-spec/operator.yml
  84. 203 0
      distributor-node/src/api-spec/public.yml
  85. 180 0
      distributor-node/src/app/index.ts
  86. 9 0
      distributor-node/src/command-base/ExitCodes.ts
  87. 162 0
      distributor-node/src/command-base/accounts.ts
  88. 40 0
      distributor-node/src/command-base/api.ts
  89. 108 0
      distributor-node/src/command-base/default.ts
  90. 58 0
      distributor-node/src/command-base/node.ts
  91. 111 0
      distributor-node/src/commands/dev/batchUpload.ts
  92. 93 0
      distributor-node/src/commands/dev/init.ts
  93. 34 0
      distributor-node/src/commands/leader/cancel-invitation.ts
  94. 25 0
      distributor-node/src/commands/leader/create-bucket-family.ts
  95. 41 0
      distributor-node/src/commands/leader/create-bucket.ts
  96. 28 0
      distributor-node/src/commands/leader/delete-bucket-family.ts
  97. 25 0
      distributor-node/src/commands/leader/delete-bucket.ts
  98. 35 0
      distributor-node/src/commands/leader/invite-bucket-operator.ts
  99. 34 0
      distributor-node/src/commands/leader/remove-bucket-operator.ts
  100. 89 0
      distributor-node/src/commands/leader/set-bucket-family-metadata.ts

+ 2 - 1
devops/vscode/settings.json

@@ -5,6 +5,7 @@
     "./tests/network-tests",
     "./types",
     "./storage-node",
-    "./atlas"
+    "./atlas",
+    "./distributor-node"
   ]
 }

+ 28 - 0
distributor-node.Dockerfile

@@ -0,0 +1,28 @@
+FROM --platform=linux/x86-64 node:14 as builder
+
+WORKDIR /joystream
+COPY ./.git .git
+COPY ./chain-metadata.json chain-metadata.json
+COPY ./types types
+COPY ./metadata-protobuf metadata-protobuf
+COPY ./distributor-node distributor-node
+COPY ./yarn.lock yarn.lock
+COPY ./package.json package.json
+
+EXPOSE 3334
+
+# Build & cleanup
+# (must be inside a signle "RUN", see: https://stackoverflow.com/questions/40212836/docker-image-larger-than-its-filesystem)
+RUN \
+  yarn --frozen-lockfile &&\
+  yarn workspace @joystream/types build &&\
+  yarn workspace @joystream/metadata-protobuf build &&\
+  yarn workspace @joystream/distributor-cli build &&\
+  find . -name "node_modules" -type d -prune &&\
+  yarn --frozen-lockfile --production &&\
+  yarn cache clean
+
+ENV CONFIG_PATH ./distributor-node/config/docker/config.docker.yml
+
+ENTRYPOINT ["yarn", "joystream-distributor"]
+CMD ["start"]

+ 2 - 0
distributor-node/.eslintignore

@@ -0,0 +1,2 @@
+src/types/generated
+src/services/networking/query-node/generated

+ 15 - 0
distributor-node/.eslintrc.js

@@ -0,0 +1,15 @@
+module.exports = {
+  env: {
+    mocha: true,
+  },
+  parserOptions: {
+    project: './tsconfig.json',
+  },
+  extends: ['@joystream/eslint-config'],
+  rules: {
+    'no-unused-vars': 'off', // Required by the typescript rule below
+    '@typescript-eslint/no-unused-vars': ['error'],
+    '@typescript-eslint/no-floating-promises': 'error',
+    'no-void': 'off',
+  },
+}

+ 9 - 0
distributor-node/.gitignore

@@ -0,0 +1,9 @@
+*-debug.log
+*-error.log
+/.nyc_output
+/dist
+/lib
+/package-lock.json
+/tmp
+node_modules
+/local

+ 4 - 0
distributor-node/.prettierignore

@@ -0,0 +1,4 @@
+/**/mock.graphql
+lib
+local
+/**/*.md

+ 40 - 0
distributor-node/README.md

@@ -0,0 +1,40 @@
+# Joystream Distributor 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)
+
+**To see the list of all available commands and their flags / arguments, check out the [commands](docs/commands/index.md) documentation.**
+
+## Configuration
+
+### Config file
+
+All the configuration values required by Joystream Distributor CLI are provided via a single configuration file (either `yml` or `json`).
+
+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
+
+### ENV variables
+
+All configuration values can be overriden using environment variables, which may be useful when running the distributor node as docker service.
+
+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`
+
+In case of arrays or `oneOf` objects (ie. `keys`), the values must be provided as json string, for example `JOYSTREAM_DISTRIBUTOR__KEYS="[{\"suri\":\"//Bob\"}]"`.
+
+In order to unset a value you can use one of the following strings as env variable value: `"off"` `"null"`, `"undefined"`, for example: `JOYSTREAM_DISTRIBUTOR__LOGS__FILE="off"`.
+
+For more envirnoment variable examples see the `distributor-node` service configuration in [docker-compose.yml](../docker-compose.yml).
+
+**For detailed configuration reference, checkout the [config schema](docs/schema/definition.md) documentation.**
+
+## Distributor Node
+
+**To understand how the distributor node works in detail, checkout the [node](docs/node/index.md) documentation.**

+ 3 - 0
distributor-node/bin/run

@@ -0,0 +1,3 @@
+#!/usr/bin/env node
+
+require('@oclif/command').run().then(require('@oclif/command/flush')).catch(require('@oclif/errors/handle'))

+ 3 - 0
distributor-node/bin/run.cmd

@@ -0,0 +1,3 @@
+@echo off
+
+node "%~dp0\run" %*

+ 40 - 0
distributor-node/config.yml

@@ -0,0 +1,40 @@
+id: test-node
+endpoints:
+  queryNode: http://localhost:8081/graphql
+  joystreamNodeWs: ws://localhost:9944
+directories:
+  assets: ./local/data
+  cacheState: ./local/cache
+logs:
+  file:
+    level: debug
+    path: ./local/logs
+    maxFiles: 30 # 30 days or 30 * 50 MB
+    maxSize: 50485760 # 50 MB
+  console:
+    level: verbose
+  # elastic:
+  #   level: info
+  #   endpoint: http://localhost:9200
+limits:
+  storage: 100G
+  maxConcurrentStorageNodeDownloads: 100
+  maxConcurrentOutboundConnections: 300
+  outboundRequestsTimeoutMs: 5000
+  pendingDownloadTimeoutSec: 3600
+  maxCachedItemSize: 1G
+intervals:
+  saveCacheState: 60
+  checkStorageNodeResponseTimes: 60
+  cacheCleanup: 60
+publicApi:
+  port: 3334
+operatorApi:
+  port: 3335
+  hmacSecret: this-is-not-so-secret
+keys:
+  - suri: //Alice
+  # - mnemonic: "escape naive annual throw tragic achieve grunt verify cram note harvest problem"
+  #   type: ed25519
+  # - keyfile: "/path/to/keyfile.json"
+workerId: 0

+ 25 - 0
distributor-node/config/docker/config.docker.yml

@@ -0,0 +1,25 @@
+id: distributor-node-docker
+endpoints:
+  queryNode: http://graphql-server-mnt:4002/graphql
+  joystreamNodeWs: ws://joystream-node:9944
+directories:
+  assets: /data
+  cacheState: /cache
+log:
+  console:
+    level: info
+limits:
+  storage: 100G
+  maxConcurrentStorageNodeDownloads: 100
+  maxConcurrentOutboundConnections: 300
+  outboundRequestsTimeoutMs: 5000
+  pendingDownloadTimeoutSec: 3600
+  maxCachedItemSize: 1G
+intervals:
+  saveCacheState: 60
+  checkStorageNodeResponseTimes: 60
+  cacheCleanup: 60
+port: 3334
+keys:
+  - suri: //Alice
+workerId: 0

+ 5 - 0
distributor-node/config/docker/filebeat.Dockerfile

@@ -0,0 +1,5 @@
+FROM docker.elastic.co/beats/filebeat:7.13.3
+COPY ./filebeat.docker.yml /usr/share/filebeat/filebeat.yml
+USER root
+RUN chown root:filebeat /usr/share/filebeat/filebeat.yml
+USER filebeat

+ 19 - 0
distributor-node/config/docker/filebeat.docker.yml

@@ -0,0 +1,19 @@
+setup.kibana:
+  host: 'kibana:5601'
+output.elasticsearch:
+  hosts: ['elasticsearch:9200']
+# Using log files:
+filebeat.inputs:
+  - type: log
+    enabled: true
+    paths: /logs/*.json
+    json.keys_under_root: true
+    json.overwrite_keys: true
+    json.add_error_key: true
+    json.expand_keys: true
+# Docker autodiscover alternative:
+# filebeat.autodiscover:
+#   providers:
+#     - type: docker
+#       hints.enabled: true
+#       hints.default_config.enabled: false

+ 76 - 0
distributor-node/docker-compose.yml

@@ -0,0 +1,76 @@
+version: '3.4'
+
+services:
+  distributor-node:
+    image: node:14
+    labels:
+      co.elastic.logs/enabled: true
+      co.elastic.logs/json.keys_under_root: true
+      co.elastic.logs/json.overwrite_keys: true
+      co.elastic.logs/json.add_error_key: true
+      co.elastic.logs/json.expand_keys: true
+    volumes:
+      - type: bind
+        source: ..
+        target: /joystream
+      - data:/data
+      - cache:/cache
+      - logs:/logs
+    networks:
+      - joystream
+    ports:
+      - 127.0.0.1:3334:3334
+    working_dir: /joystream/distributor-node
+    init: true
+    entrypoint: ["./bin/run"]
+    command: ["start", "./config/docker/distributor-dev.docker.yml"]
+  # Ref: https://www.elastic.co/guide/en/elasticsearch/reference/7.13/docker.html
+  elasticsearch:
+    image: docker.elastic.co/elasticsearch/elasticsearch:7.13.2
+    container_name: elasticsearch
+    environment:
+      - discovery.type=single-node
+      - bootstrap.memory_lock=true
+      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
+    ulimits:
+      memlock:
+        soft: -1
+        hard: -1
+    volumes:
+      - es-data:/usr/share/elasticsearch/data
+    ports:
+      - 127.0.0.1:9200:9200
+  # Ref: https://www.elastic.co/guide/en/kibana/7.13/docker.html
+  kibana:
+    image: docker.elastic.co/kibana/kibana:7.13.2
+    container_name: kibana
+    ports:
+      - 127.0.0.1:5601:5601
+    environment:
+      ELASTICSEARCH_HOSTS: http://elasticsearch:9200
+  # Ref: https://www.elastic.co/guide/en/beats/filebeat/current/running-on-docker.html
+  filebeat:
+    user: root
+    image: joystream/distributor-filebeat
+    build:
+      context: ./config/docker
+      dockerfile: ./filebeat.Dockerfile
+    volumes:
+      - /var/run/docker.sock:/var/run/docker.sock:ro
+      - logs:/logs
+
+volumes:
+  es-data:
+    driver: local
+  logs:
+    driver: local
+  cache:
+    driver: local
+  data:
+    driver: local
+
+# Join default joystream network (from root docker-compose)
+networks:
+  joystream:
+    external: true
+    name: joystream_default

+ 375 - 0
distributor-node/docs/api/operator/index.md

@@ -0,0 +1,375 @@
+---
+title: Distributor node operator API v0.1.0
+language_tabs:
+  - javascript: JavaScript
+  - shell: Shell
+language_clients:
+  - javascript: ""
+  - shell: ""
+toc_footers: []
+includes: []
+search: true
+highlight_theme: darkula
+headingLevel: 2
+
+---
+
+<!-- AUTO-GENERATED-CONTENT:START (TOC) -->
+<!-- AUTO-GENERATED-CONTENT:END -->
+
+<h1 id="distributor-node-operator-api">Distributor node operator API v0.1.0</h1>
+
+> Scroll down for code samples, example requests and responses.
+
+Distributor node operator API
+
+Base URLs:
+
+* <a href="http://localhost:3335/api/v1/">http://localhost:3335/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>
+
+undefined
+
+<h1 id="distributor-node-operator-api-default">Default</h1>
+
+## operator.stopApi
+
+<a id="opIdoperator.stopApi"></a>
+
+> Code samples
+
+```javascript
+
+const headers = {
+  'Authorization':'Bearer {access-token}'
+};
+
+fetch('http://localhost:3335/api/v1/stop-api',
+{
+  method: 'POST',
+
+  headers: headers
+})
+.then(function(res) {
+    return res.json();
+}).then(function(body) {
+    console.log(body);
+});
+
+```
+
+```shell
+# You can also use wget
+curl -X POST http://localhost:3335/api/v1/stop-api \
+  -H 'Authorization: Bearer {access-token}'
+
+```
+
+`POST /stop-api`
+
+Turns off the public api.
+
+<h3 id="operator.stopapi-responses">Responses</h3>
+
+|Status|Meaning|Description|Schema|
+|---|---|---|---|
+|200|[OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)|OK|None|
+|401|[Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)|Not authorized|None|
+|409|[Conflict](https://tools.ietf.org/html/rfc7231#section-6.5.8)|Already stopped|None|
+|500|[Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)|Unexpected server error|None|
+
+<aside class="warning">
+To perform this operation, you must be authenticated by means of one of the following methods:
+OperatorAuth
+</aside>
+
+## operator.startApi
+
+<a id="opIdoperator.startApi"></a>
+
+> Code samples
+
+```javascript
+
+const headers = {
+  'Authorization':'Bearer {access-token}'
+};
+
+fetch('http://localhost:3335/api/v1/start-api',
+{
+  method: 'POST',
+
+  headers: headers
+})
+.then(function(res) {
+    return res.json();
+}).then(function(body) {
+    console.log(body);
+});
+
+```
+
+```shell
+# You can also use wget
+curl -X POST http://localhost:3335/api/v1/start-api \
+  -H 'Authorization: Bearer {access-token}'
+
+```
+
+`POST /start-api`
+
+Turns on the public api.
+
+<h3 id="operator.startapi-responses">Responses</h3>
+
+|Status|Meaning|Description|Schema|
+|---|---|---|---|
+|200|[OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)|OK|None|
+|401|[Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)|Not authorized|None|
+|409|[Conflict](https://tools.ietf.org/html/rfc7231#section-6.5.8)|Already started|None|
+|500|[Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)|Unexpected server error|None|
+
+<aside class="warning">
+To perform this operation, you must be authenticated by means of one of the following methods:
+OperatorAuth
+</aside>
+
+## operator.shutdown
+
+<a id="opIdoperator.shutdown"></a>
+
+> Code samples
+
+```javascript
+
+const headers = {
+  'Authorization':'Bearer {access-token}'
+};
+
+fetch('http://localhost:3335/api/v1/shutdown',
+{
+  method: 'POST',
+
+  headers: headers
+})
+.then(function(res) {
+    return res.json();
+}).then(function(body) {
+    console.log(body);
+});
+
+```
+
+```shell
+# You can also use wget
+curl -X POST http://localhost:3335/api/v1/shutdown \
+  -H 'Authorization: Bearer {access-token}'
+
+```
+
+`POST /shutdown`
+
+Shuts down the node.
+
+<h3 id="operator.shutdown-responses">Responses</h3>
+
+|Status|Meaning|Description|Schema|
+|---|---|---|---|
+|200|[OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)|OK|None|
+|401|[Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)|Not authorized|None|
+|409|[Conflict](https://tools.ietf.org/html/rfc7231#section-6.5.8)|Already shutting down|None|
+|500|[Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)|Unexpected server error|None|
+
+<aside class="warning">
+To perform this operation, you must be authenticated by means of one of the following methods:
+OperatorAuth
+</aside>
+
+## operator.setWorker
+
+<a id="opIdoperator.setWorker"></a>
+
+> Code samples
+
+```javascript
+const inputBody = '{
+  "workerId": 0
+}';
+const headers = {
+  'Content-Type':'application/json',
+  'Authorization':'Bearer {access-token}'
+};
+
+fetch('http://localhost:3335/api/v1/set-worker',
+{
+  method: 'POST',
+  body: inputBody,
+  headers: headers
+})
+.then(function(res) {
+    return res.json();
+}).then(function(body) {
+    console.log(body);
+});
+
+```
+
+```shell
+# You can also use wget
+curl -X POST http://localhost:3335/api/v1/set-worker \
+  -H 'Content-Type: application/json' \
+  -H 'Authorization: Bearer {access-token}'
+
+```
+
+`POST /set-worker`
+
+Updates the operator worker id.
+
+> Body parameter
+
+```json
+{
+  "workerId": 0
+}
+```
+
+<h3 id="operator.setworker-parameters">Parameters</h3>
+
+|Name|In|Type|Required|Description|
+|---|---|---|---|---|
+|body|body|[SetWorkerOperation](#schemasetworkeroperation)|false|none|
+
+<h3 id="operator.setworker-responses">Responses</h3>
+
+|Status|Meaning|Description|Schema|
+|---|---|---|---|
+|200|[OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)|OK|None|
+|401|[Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)|Not authorized|None|
+|500|[Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)|Unexpected server error|None|
+
+<aside class="warning">
+To perform this operation, you must be authenticated by means of one of the following methods:
+OperatorAuth
+</aside>
+
+## operator.setBuckets
+
+<a id="opIdoperator.setBuckets"></a>
+
+> Code samples
+
+```javascript
+const inputBody = '{
+  "buckets": [
+    "string"
+  ]
+}';
+const headers = {
+  'Content-Type':'application/json',
+  'Authorization':'Bearer {access-token}'
+};
+
+fetch('http://localhost:3335/api/v1/set-buckets',
+{
+  method: 'POST',
+  body: inputBody,
+  headers: headers
+})
+.then(function(res) {
+    return res.json();
+}).then(function(body) {
+    console.log(body);
+});
+
+```
+
+```shell
+# You can also use wget
+curl -X POST http://localhost:3335/api/v1/set-buckets \
+  -H 'Content-Type: application/json' \
+  -H 'Authorization: Bearer {access-token}'
+
+```
+
+`POST /set-buckets`
+
+Updates buckets supported by the node.
+
+> Body parameter
+
+```json
+{
+  "buckets": [
+    "string"
+  ]
+}
+```
+
+<h3 id="operator.setbuckets-parameters">Parameters</h3>
+
+|Name|In|Type|Required|Description|
+|---|---|---|---|---|
+|body|body|[SetBucketsOperation](#schemasetbucketsoperation)|false|none|
+
+<h3 id="operator.setbuckets-responses">Responses</h3>
+
+|Status|Meaning|Description|Schema|
+|---|---|---|---|
+|200|[OK](https://tools.ietf.org/html/rfc7231#section-6.3.1)|OK|None|
+|401|[Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1)|Not authorized|None|
+|500|[Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1)|Unexpected server error|None|
+
+<aside class="warning">
+To perform this operation, you must be authenticated by means of one of the following methods:
+OperatorAuth
+</aside>
+
+# Schemas
+
+<h2 id="tocS_SetWorkerOperation">SetWorkerOperation</h2>
+
+<a id="schemasetworkeroperation"></a>
+<a id="schema_SetWorkerOperation"></a>
+<a id="tocSsetworkeroperation"></a>
+<a id="tocssetworkeroperation"></a>
+
+```json
+{
+  "workerId": 0
+}
+
+```
+
+### Properties
+
+|Name|Type|Required|Restrictions|Description|
+|---|---|---|---|---|
+|workerId|integer|true|none|none|
+
+<h2 id="tocS_SetBucketsOperation">SetBucketsOperation</h2>
+
+<a id="schemasetbucketsoperation"></a>
+<a id="schema_SetBucketsOperation"></a>
+<a id="tocSsetbucketsoperation"></a>
+<a id="tocssetbucketsoperation"></a>
+
+```json
+{
+  "buckets": [
+    "string"
+  ]
+}
+
+```
+
+### Properties
+
+|Name|Type|Required|Restrictions|Description|
+|---|---|---|---|---|
+|buckets|[string]|false|none|Set of bucket ids to be distributed by the node. If not provided - all buckets assigned to currently configured worker will be distributed.|
+
+undefined
+

+ 382 - 0
distributor-node/docs/api/public/index.md

@@ -0,0 +1,382 @@
+---
+title: Distributor node public 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 public API</a>
+includes: []
+search: true
+highlight_theme: darkula
+headingLevel: 2
+
+---
+
+<!-- AUTO-GENERATED-CONTENT:START (TOC) -->
+<!-- AUTO-GENERATED-CONTENT:END -->
+
+<h1 id="distributor-node-public-api">Distributor node public API v0.1.0</h1>
+
+> Scroll down for code samples, example requests and responses.
+
+Distributor node public 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-public-api-default">Default</h1>
+
+## 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": [
+    "string"
+  ]
+}
+```
+
+<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/assets/{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/assets/{objectId}
+
+```
+
+`HEAD /assets/{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/assets/{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/assets/{objectId} \
+  -H 'Accept: image/*'
+
+```
+
+`GET /assets/{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": [
+    "string"
+  ]
+}
+
+```
+
+### Properties
+
+oneOf
+
+|Name|Type|Required|Restrictions|Description|
+|---|---|---|---|---|
+|*anonymous*|object|false|none|none|
+|» bucketIds|[string]|true|none|none|
+
+xor
+
+|Name|Type|Required|Restrictions|Description|
+|---|---|---|---|---|
+|*anonymous*|object|false|none|none|
+|» allByWorkerId|integer|true|none|none|
+
+undefined
+

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

@@ -0,0 +1,142 @@
+<!-- AUTO-GENERATED-CONTENT:START (TOC) -->
+<!-- AUTO-GENERATED-CONTENT:END -->
+
+{{= 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}}
+{{?}}

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

@@ -0,0 +1,46 @@
+`joystream-distributor dev`
+===========================
+
+Developer utility commands
+
+* [`joystream-distributor dev:batchUpload`](#joystream-distributor-devbatchupload)
+* [`joystream-distributor dev:init`](#joystream-distributor-devinit)
+
+## `joystream-distributor dev:batchUpload`
+
+```
+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)
+
+  -e, --endpoint=endpoint          (required)
+
+  -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.
+
+```
+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)_

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

@@ -0,0 +1,23 @@
+`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
+
+```
+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/v3.2.2/src/commands/help.ts)_

+ 5 - 0
distributor-node/docs/commands/index.md

@@ -0,0 +1,5 @@
+- [`joystream-distributor help` command](./help.md)
+- [`joystream-distributor start` command](./start.md)
+- [`joystream-distributor leader:*` commands](./leader.md)
+- [`joystream-distributor operator:*` commands](./operator.md)
+- [`joystream-distributor dev:*` commands](./dev.md)

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

@@ -0,0 +1,322 @@
+`joystream-distributor leader`
+==============================
+
+Commands for performing Distribution Working Group leader on-chain duties (like setting distribution module limits and parameters, assigning bags and buckets etc.)
+
+* [`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.
+
+```
+USAGE
+  $ joystream-distributor leader:cancel-invitation
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket ID in {familyId}:{bucketIndex} format.
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -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 in {familyId}:{bucketIndex} format.
+
+  -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/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 in {familyId}:{bucketIndex} format.
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -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).
+
+```
+USAGE
+  $ joystream-distributor leader:remove-bucket-operator
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket ID in {familyId}:{bucketIndex} format.
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -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.
+
+```
+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.
+
+```
+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: ] Index(es) (within the family) of bucket(s) to add to the 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: ] Index(es) (within the family) of bucket(s) to remove from the bag
+
+  -y, --yes
+      Answer "yes" to any prompt, skipping any manual confirmations
+
+EXAMPLE
+  $ joystream-distributor leader:update-bag -b 1 -f 1 -a 1 2 3 -r 4 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 in {familyId}:{bucketIndex} format.
+
+  -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)
+
+  -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 in {familyId}:{bucketIndex} format.
+  -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)
+
+  -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          [default: ] 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 2:10 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)_

+ 126 - 0
distributor-node/docs/commands/node.md

@@ -0,0 +1,126 @@
+`joystream-distributor node`
+============================
+
+Commands for interacting with a running distributor node through OperatorApi
+
+* [`joystream-distributor node:set-buckets`](#joystream-distributor-nodeset-buckets)
+* [`joystream-distributor node:set-worker`](#joystream-distributor-nodeset-worker)
+* [`joystream-distributor node:shutdown`](#joystream-distributor-nodeshutdown)
+* [`joystream-distributor node:start-public-api`](#joystream-distributor-nodestart-public-api)
+* [`joystream-distributor node:stop-public-api`](#joystream-distributor-nodestop-public-api)
+
+## `joystream-distributor node:set-buckets`
+
+Send an api request to change the set of buckets distributed by given distributor node.
+
+```
+USAGE
+  $ joystream-distributor node:set-buckets
+
+OPTIONS
+  -B, --bucketIds=bucketIds    Set of bucket ids to distribute. Each bucket id should be in {familyId}:{bucketIndex}
+                               format. Multiple ids can be provided, separated by space.
+
+  -a, --all                    Distribute all buckets belonging to configured worker
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -s, --secret=secret          HMAC secret key to use (will default to config.operatorApi.hmacSecret if present)
+
+  -u, --url=url                (required) Distributor node operator api base url (ie. http://localhost:3335)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+
+EXAMPLES
+  $ joystream-distributor node:set-buckets --bucketIds 1:1 1:2 1:3 2:1 2:2
+  $ joystream-distributor node:set-buckets --all
+```
+
+_See code: [src/commands/node/set-buckets.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/node/set-buckets.ts)_
+
+## `joystream-distributor node:set-worker`
+
+Send an api request to change workerId assigned to given distributor node instance.
+
+```
+USAGE
+  $ joystream-distributor node:set-worker
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -s, --secret=secret          HMAC secret key to use (will default to config.operatorApi.hmacSecret if present)
+
+  -u, --url=url                (required) Distributor node operator api base url (ie. http://localhost:3335)
+
+  -w, --workerId=workerId      (required) New workerId to set
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/node/set-worker.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/node/set-worker.ts)_
+
+## `joystream-distributor node:shutdown`
+
+Send an api request to shutdown given distributor node.
+
+```
+USAGE
+  $ joystream-distributor node:shutdown
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -s, --secret=secret          HMAC secret key to use (will default to config.operatorApi.hmacSecret if present)
+
+  -u, --url=url                (required) Distributor node operator api base url (ie. http://localhost:3335)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/node/shutdown.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/node/shutdown.ts)_
+
+## `joystream-distributor node:start-public-api`
+
+Send an api request to start public api of given distributor node.
+
+```
+USAGE
+  $ joystream-distributor node:start-public-api
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -s, --secret=secret          HMAC secret key to use (will default to config.operatorApi.hmacSecret if present)
+
+  -u, --url=url                (required) Distributor node operator api base url (ie. http://localhost:3335)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/node/start-public-api.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/node/start-public-api.ts)_
+
+## `joystream-distributor node:stop-public-api`
+
+Send an api request to stop public api of given distributor node.
+
+```
+USAGE
+  $ joystream-distributor node:stop-public-api
+
+OPTIONS
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -s, --secret=secret          HMAC secret key to use (will default to config.operatorApi.hmacSecret if present)
+
+  -u, --url=url                (required) Distributor node operator api base url (ie. http://localhost:3335)
+
+  -y, --yes                    Answer "yes" to any prompt, skipping any manual confirmations
+```
+
+_See code: [src/commands/node/stop-public-api.ts](https://github.com/Joystream/joystream/blob/v0.1.0/src/commands/node/stop-public-api.ts)_

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

@@ -0,0 +1,59 @@
+`joystream-distributor operator`
+================================
+
+Commands for performing node operator (Distribution Working Group worker) on-chain duties (like accepting bucket invitations, setting node metadata)
+
+* [`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.
+
+```
+USAGE
+  $ joystream-distributor operator:accept-invitation
+
+OPTIONS
+  -B, --bucketId=bucketId      (required) Distribution bucket ID in {familyId}:{bucketIndex} format.
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -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 in {familyId}:{bucketIndex} format.
+
+  -c, --configPath=configPath  [default: ./config.yml] Path to config JSON/YAML file (relative to current working
+                               directory)
+
+  -e, --endpoint=endpoint      Root distribution node endpoint
+
+  -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)_

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

@@ -0,0 +1,23 @@
+`joystream-distributor start`
+=============================
+
+Start the node
+
+* [`joystream-distributor start`](#joystream-distributor-start)
+
+## `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)_

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

@@ -0,0 +1,415 @@
+<!-- AUTO-GENERATED-CONTENT:START (TOC:firsth1=true) -->
+- [API](#api)
+  - [Public API](#public-api)
+  - [Operator API](#operator-api)
+  - [Requesting assets](#requesting-assets)
+    - [Scenario 1 (cache hit)](#scenario-1-cache-hit)
+    - [Scenario 2 (pending)](#scenario-2-pending)
+      - [Scenario 2.1: No `Range` header was provided with a request or the `Range` start is `<= partiallyDownloadedContentSize`](#scenario-21-no-range-header-was-provided-with-a-request-or-the-range-start-is--partiallydownloadedcontentsize)
+      - [Scenario 2.2: `Range` header was provided with a request and `Range` start is `> partiallyDownloadedContentSize`](#scenario-22-range-header-was-provided-with-a-request-and-range-start-is--partiallydownloadedcontentsize)
+    - [Scenario 3 (cache miss)](#scenario-3-cache-miss)
+      - [Scenario 3.1: The requested data object is not found](#scenario-31-the-requested-data-object-is-not-found)
+      - [Scenario 3.2: The object is not distributed by the node](#scenario-32-the-object-is-not-distributed-by-the-node)
+      - [Scenario 3.3: The request is valid, the node needs to fetch the missing object](#scenario-33-the-request-is-valid-the-node-needs-to-fetch-the-missing-object)
+  - [Checking asset status](#checking-asset-status)
+  - [API limits](#api-limits)
+    - [Example Nginx configuration](#example-nginx-configuration)
+    - [System configuration](#system-configuration)
+- [Data fetching](#data-fetching)
+  - [Finding nearby storage nodes:](#finding-nearby-storage-nodes)
+  - [Data object fetching flow](#data-object-fetching-flow)
+- [Metadata](#metadata)
+  - [DistributionBucketFamilyMetadata](#distributionbucketfamilymetadata)
+    - [Geographical areas covered by the distirbution bucket family](#geographical-areas-covered-by-the-distirbution-bucket-family)
+    - [Using latency tests for choosing a family](#using-latency-tests-for-choosing-a-family)
+  - [Distribution bucket operator metadata](#distribution-bucket-operator-metadata)
+- [State](#state)
+- [Caching](#caching)
+  - [Caching policy](#caching-policy)
+    - [LRU groups](#lru-groups)
+  - [Cache cleanup](#cache-cleanup)
+- [Logging](#logging)
+- [Query node integration](#query-node-integration)
+<!-- AUTO-GENERATED-CONTENT:END -->
+
+<a name="the-api"></a>
+
+# API
+
+The Distributor Node, depending on the configuration, can expose either one or two HTTP APIs, both implemented with [ExpressJS](https://expressjs.com/).
+
+## Public API
+
+Public API is enabled by default and can be used to retrieve assets from the node as well as some basic information about its current status.
+
+Public API is described by an [OpenAPI](https://swagger.io/specification/) schema located at _[src/api-spec/public.yml](../../src/api-spec/public.yml)_
+
+**Full public API documentation can be found [here](../api/public/index.md)**
+
+## Operator API
+
+Secured operator API can be enabled with [`config.operatorApi`](../schema/definition-properties-operatorapi.md).
+Operator API makes it possible to remotely execute some operations on a running node (ie. changing supported buckets).
+
+Operator API is described by an [OpenAPI](https://swagger.io/specification/) schema located at _[src/api-spec/operator.yml](../../src/api-spec/operator.yml)_
+
+**Full operator API documentation can be found [here](../api/operator/index.md)**
+
+<a name="requesting-assets"></a>
+
+## Requesting assets
+
+The assets are requested from the distributor node by using a `GET` request to [`/assets/{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](#caching-policy) is updated
+- The [`send`](https://www.npmjs.com/package/send) library is used to handle the request and serve the object. The library supports, among others, partial responses (`Ranges`) and conditional-GET negotiation (`If-Match`, `If-Unmodified-Since`, `If-None-Match`, `If-Modified-Since`).
+- `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)
+- `x-cache: hit` and `x-data-source: local` headers are sent, providing the client detailed information about the triggered scenario (see: [_public.assets Responses_](../api/index.md#public.asset-responses)).
+
+<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 with a request 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 into the local file, as it's being downloaded from the storage node, is beeing simultaneously read from the file (using a small interval) and 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 (see: [_public.assets Responses_](../api/index.md#public.asset-responses)).
+
+<a name="scenario-2-2"></a>
+
+#### Scenario 2.2: `Range` header was provided with a request and `Range` start is `> partiallyDownloadedContentSize`
+
+In this case streaming the response from partially downloaded file, like in the scenario above, may cause unnecessary delay, because 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) via [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 (see: [_public.assets Responses_](../api/index.md#public.asset-responses)).
+
+<a name="scenario-3"></a>
+### Scenario 3 (cache miss)
+
+In this case the distributor node is making an additional request to the query node in order to fetch details of the requested object, including:
+- 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 an asset status without affecting the distributor node state in any way (for example - by triggering the process of [fetching the missing data object](#data-fetching)), by sending a [`HEAD` request to `/assets/{objectId}`](../api/index.md#opIdpublic.assetHead) endpoint.
+
+If the request is valid, the node will respond with, among others, the `x-cache`, `content-length`, `cache-control` headers.
+
+In case the request is not invalid, the node will respond with the same status code it would in case of an invalid `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) however 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, keep in mind that a lot of simultaneous connections may also cause some OS limits to 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.md#checkstoragenoderesponsetimes) 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 re-tried 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
+        latencyTestTargets
+        areas {
+          area {
+            __typename
+            ...on GeographicalAreaCountry {
+              countryCode: code
+            }
+            ...on GeographicalAreaContinent {
+              continentCode: code
+            }
+            ...on GeographicalAreaSubdivistion {
+              subdivisionCode: code
+            }
+          }
+        }
+      }
+    }
+    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 good-enough 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 (recreated on startup) and persistent state (stored in filesystem).
+
+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.md#savecachestate) 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.md#maxconcurrentstoragenodedownloads) 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 looking for 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.md#storage) 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.md#cachecleanup) 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 priority.
+
+The logs can be directed to some of the 3 available outputs, depending on the [`logs`](../schema/definition-properties-logs.md) configuration settings:
+- console ([`logs.console`](../schema/definition-properties-logs-properties-console.md))
+- log file(s) ([`logs.file`](../schema/definition-properties-logs-properties-file.md))
+- an elasticsearch endpoint ([`logs.elastic`](../schema/definition-properties-logs-properties-elastic.md))
+
+# Query node integration
+
+Because the distributor node is making requests to a query node:
+- on [cache miss](#scenario-3)
+- periodically, for [cache cleanup](#cache-cleanup) purposes
+
+In order to achieve the best perfomance it is recommended to either run the query-node processor and graphql server on the same machine the distributor node will be running on, or use a query node endpoint that can be accessed with a minimal latency.
+
+Taking the [docker-compose.yml](../../docker-compose.yml) example, the services that could be run on the same machine may include:
+- `db`
+- `processor`
+- `graphql-server`
+- `distributor-node`
+
+The `INDEXER_ENDPOINT_URL` can be point to a completely external indexer endpoint, as the latency between `processor` and `indexer` is less of an issue in this case.

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

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

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

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

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

@@ -0,0 +1,46 @@
+## directories Type
+
+`object` ([Details](definition-properties-directories.md))
+
+# directories Properties
+
+| Property                  | Type     | Required | Nullable       | Defined by                                                                                                                                                                              |
+| :------------------------ | :------- | :------- | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [assets](#assets)         | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-directories-properties-assets.md "https://joystream.org/schemas/argus/config#/properties/directories/properties/assets")         |
+| [cacheState](#cachestate) | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-directories-properties-cachestate.md "https://joystream.org/schemas/argus/config#/properties/directories/properties/cacheState") |
+
+## assets
+
+Path to a directory where all the cached assets will be stored
+
+`assets`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-directories-properties-assets.md "https://joystream.org/schemas/argus/config#/properties/directories/properties/assets")
+
+### assets Type
+
+`string`
+
+## cacheState
+
+Path to a directory where information about the current cache state will be stored (LRU-SP cache data, stored assets mime types etc.)
+
+`cacheState`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-directories-properties-cachestate.md "https://joystream.org/schemas/argus/config#/properties/directories/properties/cacheState")
+
+### cacheState Type
+
+`string`

+ 13 - 0
distributor-node/docs/schema/definition-properties-distributed-buckets-ids-items.md

@@ -0,0 +1,13 @@
+## items Type
+
+`string`
+
+## items Constraints
+
+**pattern**: the string must match the following regular expression: 
+
+```regexp
+^[0-9]+:[0-9]+$
+```
+
+[try pattern](https://regexr.com/?expression=%5E%5B0-9%5D%2B%3A%5B0-9%5D%2B%24 "try regular expression with regexr.com")

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

@@ -0,0 +1,9 @@
+## buckets Type
+
+`string[]`
+
+## buckets Constraints
+
+**minimum number of items**: the minimum number of items for this array is: `1`
+
+**unique items**: all items in this array must be unique. Duplicates are not allowed.

+ 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`

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

@@ -0,0 +1,46 @@
+## 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 "https://joystream.org/schemas/argus/config#/properties/endpoints/properties/queryNode")             |
+| [joystreamNodeWs](#joystreamnodews) | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-endpoints-properties-joystreamnodews.md "https://joystream.org/schemas/argus/config#/properties/endpoints/properties/joystreamNodeWs") |
+
+## 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 "https://joystream.org/schemas/argus/config#/properties/endpoints/properties/queryNode")
+
+### queryNode Type
+
+`string`
+
+## joystreamNodeWs
+
+Joystream node websocket api uri (for example: ws\://localhost:9944)
+
+`joystreamNodeWs`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-endpoints-properties-joystreamnodews.md "https://joystream.org/schemas/argus/config#/properties/endpoints/properties/joystreamNodeWs")
+
+### joystreamNodeWs Type
+
+`string`

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

@@ -0,0 +1,7 @@
+## id Type
+
+`string`
+
+## id Constraints
+
+**minimum length**: the minimum number of characters for this string is: `1`

+ 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 "https://joystream.org/schemas/argus/config#/properties/intervals/properties/saveCacheState")                               |
+| [checkStorageNodeResponseTimes](#checkstoragenoderesponsetimes) | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-intervals-properties-checkstoragenoderesponsetimes.md "https://joystream.org/schemas/argus/config#/properties/intervals/properties/checkStorageNodeResponseTimes") |
+| [cacheCleanup](#cachecleanup)                                   | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-intervals-properties-cachecleanup.md "https://joystream.org/schemas/argus/config#/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 "https://joystream.org/schemas/argus/config#/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 "https://joystream.org/schemas/argus/config#/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 "https://joystream.org/schemas/argus/config#/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-oneof-json-backup-file-properties-keyfile.md

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

+ 27 - 0
distributor-node/docs/schema/definition-properties-keys-items-oneof-json-backup-file.md

@@ -0,0 +1,27 @@
+## 2 Type
+
+`object` ([JSON backup file](definition-properties-keys-items-oneof-json-backup-file.md))
+
+# 2 Properties
+
+| Property            | Type     | Required | Nullable       | Defined by                                                                                                                                                                                                     |
+| :------------------ | :------- | :------- | :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [keyfile](#keyfile) | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-keys-items-oneof-json-backup-file-properties-keyfile.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/2/properties/keyfile") |
+
+## keyfile
+
+
+
+`keyfile`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-keys-items-oneof-json-backup-file-properties-keyfile.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/2/properties/keyfile")
+
+### keyfile Type
+
+`string`

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

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

+ 21 - 0
distributor-node/docs/schema/definition-properties-keys-items-oneof-mnemonic-phrase-properties-type.md

@@ -0,0 +1,21 @@
+## type Type
+
+`string`
+
+## type Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"ed25519"` |             |
+| `"sr25519"` |             |
+| `"ecdsa"`   |             |
+
+## type Default Value
+
+The default value is:
+
+```json
+"sr25519"
+```

+ 64 - 0
distributor-node/docs/schema/definition-properties-keys-items-oneof-mnemonic-phrase.md

@@ -0,0 +1,64 @@
+## 1 Type
+
+`object` ([Mnemonic phrase](definition-properties-keys-items-oneof-mnemonic-phrase.md))
+
+# 1 Properties
+
+| Property              | Type     | Required | Nullable       | Defined by                                                                                                                                                                                                      |
+| :-------------------- | :------- | :------- | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [type](#type)         | `string` | Optional | cannot be null | [Distributor node configuration](definition-properties-keys-items-oneof-mnemonic-phrase-properties-type.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/1/properties/type")         |
+| [mnemonic](#mnemonic) | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-keys-items-oneof-mnemonic-phrase-properties-mnemonic.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/1/properties/mnemonic") |
+
+## type
+
+
+
+`type`
+
+*   is optional
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-keys-items-oneof-mnemonic-phrase-properties-type.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/1/properties/type")
+
+### type Type
+
+`string`
+
+### type Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"ed25519"` |             |
+| `"sr25519"` |             |
+| `"ecdsa"`   |             |
+
+### type Default Value
+
+The default value is:
+
+```json
+"sr25519"
+```
+
+## mnemonic
+
+
+
+`mnemonic`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-keys-items-oneof-mnemonic-phrase-properties-mnemonic.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/1/properties/mnemonic")
+
+### mnemonic Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-keys-items-oneof-substrate-uri-properties-suri.md

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

+ 21 - 0
distributor-node/docs/schema/definition-properties-keys-items-oneof-substrate-uri-properties-type.md

@@ -0,0 +1,21 @@
+## type Type
+
+`string`
+
+## type Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"ed25519"` |             |
+| `"sr25519"` |             |
+| `"ecdsa"`   |             |
+
+## type Default Value
+
+The default value is:
+
+```json
+"sr25519"
+```

+ 64 - 0
distributor-node/docs/schema/definition-properties-keys-items-oneof-substrate-uri.md

@@ -0,0 +1,64 @@
+## 0 Type
+
+`object` ([Substrate uri](definition-properties-keys-items-oneof-substrate-uri.md))
+
+# 0 Properties
+
+| Property      | Type     | Required | Nullable       | Defined by                                                                                                                                                                                            |
+| :------------ | :------- | :------- | :------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [type](#type) | `string` | Optional | cannot be null | [Distributor node configuration](definition-properties-keys-items-oneof-substrate-uri-properties-type.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/0/properties/type") |
+| [suri](#suri) | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-keys-items-oneof-substrate-uri-properties-suri.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/0/properties/suri") |
+
+## type
+
+
+
+`type`
+
+*   is optional
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-keys-items-oneof-substrate-uri-properties-type.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/0/properties/type")
+
+### type Type
+
+`string`
+
+### type Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"ed25519"` |             |
+| `"sr25519"` |             |
+| `"ecdsa"`   |             |
+
+### type Default Value
+
+The default value is:
+
+```json
+"sr25519"
+```
+
+## suri
+
+
+
+`suri`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-keys-items-oneof-substrate-uri-properties-suri.md "https://joystream.org/schemas/argus/config#/properties/keys/items/oneOf/0/properties/suri")
+
+### suri Type
+
+`string`

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

@@ -0,0 +1,11 @@
+## items Type
+
+merged type ([Details](definition-properties-keys-items.md))
+
+one (and only one) of
+
+*   [Substrate uri](definition-properties-keys-items-oneof-substrate-uri.md "check type definition")
+
+*   [Mnemonic phrase](definition-properties-keys-items-oneof-mnemonic-phrase.md "check type definition")
+
+*   [JSON backup file](definition-properties-keys-items-oneof-json-backup-file.md "check type definition")

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

@@ -0,0 +1,7 @@
+## keys Type
+
+an array of merged types ([Details](definition-properties-keys-items.md))
+
+## keys Constraints
+
+**minimum number of items**: the minimum number of items for this array is: `1`

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

@@ -0,0 +1,15 @@
+## dataObjectSourceByObjectIdTTL Type
+
+`integer`
+
+## dataObjectSourceByObjectIdTTL Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`
+
+## dataObjectSourceByObjectIdTTL Default Value
+
+The default value is:
+
+```json
+60
+```

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

@@ -0,0 +1,13 @@
+## maxCachedItemSize Type
+
+`string`
+
+## maxCachedItemSize 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")

+ 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-outboundrequeststimeoutms.md

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

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

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

+ 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")

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

@@ -0,0 +1,189 @@
+## 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 "https://joystream.org/schemas/argus/config#/properties/limits/properties/storage")                                                     |
+| [maxConcurrentStorageNodeDownloads](#maxconcurrentstoragenodedownloads) | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-limits-properties-maxconcurrentstoragenodedownloads.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/maxConcurrentStorageNodeDownloads") |
+| [maxConcurrentOutboundConnections](#maxconcurrentoutboundconnections)   | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-limits-properties-maxconcurrentoutboundconnections.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/maxConcurrentOutboundConnections")   |
+| [outboundRequestsTimeoutMs](#outboundrequeststimeoutms)                 | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-limits-properties-outboundrequeststimeoutms.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/outboundRequestsTimeoutMs")                 |
+| [pendingDownloadTimeoutSec](#pendingdownloadtimeoutsec)                 | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-limits-properties-pendingdownloadtimeoutsec.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/pendingDownloadTimeoutSec")                 |
+| [maxCachedItemSize](#maxcacheditemsize)                                 | `string`  | Optional | cannot be null | [Distributor node configuration](definition-properties-limits-properties-maxcacheditemsize.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/maxCachedItemSize")                                 |
+| [dataObjectSourceByObjectIdTTL](#dataobjectsourcebyobjectidttl)         | `integer` | Optional | cannot be null | [Distributor node configuration](definition-properties-limits-properties-dataobjectsourcebyobjectidttl.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/dataObjectSourceByObjectIdTTL")         |
+
+## 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 "https://joystream.org/schemas/argus/config#/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 "https://joystream.org/schemas/argus/config#/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) (excluding proxy connections)
+
+`maxConcurrentOutboundConnections`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits-properties-maxconcurrentoutboundconnections.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/maxConcurrentOutboundConnections")
+
+### maxConcurrentOutboundConnections Type
+
+`integer`
+
+### maxConcurrentOutboundConnections Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`
+
+## outboundRequestsTimeoutMs
+
+Timeout for all outbound storage node http requests in miliseconds
+
+`outboundRequestsTimeoutMs`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits-properties-outboundrequeststimeoutms.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/outboundRequestsTimeoutMs")
+
+### outboundRequestsTimeoutMs Type
+
+`integer`
+
+### outboundRequestsTimeoutMs Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1000`
+
+## pendingDownloadTimeoutSec
+
+Timeout for pending storage node downloads in seconds
+
+`pendingDownloadTimeoutSec`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits-properties-pendingdownloadtimeoutsec.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/pendingDownloadTimeoutSec")
+
+### pendingDownloadTimeoutSec Type
+
+`integer`
+
+### pendingDownloadTimeoutSec Constraints
+
+**minimum**: the value of this number must greater than or equal to: `60`
+
+## maxCachedItemSize
+
+Maximum size of a data object allowed to be cached by the node
+
+`maxCachedItemSize`
+
+*   is optional
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits-properties-maxcacheditemsize.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/maxCachedItemSize")
+
+### maxCachedItemSize Type
+
+`string`
+
+### maxCachedItemSize 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")
+
+## dataObjectSourceByObjectIdTTL
+
+TTL (in seconds) for dataObjectSourceByObjectId cache used when proxying objects of size greater than maxCachedItemSize to the right storage node.
+
+`dataObjectSourceByObjectIdTTL`
+
+*   is optional
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-limits-properties-dataobjectsourcebyobjectidttl.md "https://joystream.org/schemas/argus/config#/properties/limits/properties/dataObjectSourceByObjectIdTTL")
+
+### dataObjectSourceByObjectIdTTL Type
+
+`integer`
+
+### dataObjectSourceByObjectIdTTL Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`
+
+### dataObjectSourceByObjectIdTTL Default Value
+
+The default value is:
+
+```json
+60
+```

+ 41 - 0
distributor-node/docs/schema/definition-properties-logs-properties-console-logging-options.md

@@ -0,0 +1,41 @@
+## console Type
+
+`object` ([Console logging options](definition-properties-logs-properties-console-logging-options.md))
+
+# console Properties
+
+| Property        | Type     | Required | Nullable       | Defined by                                                                                                                                                                                                         |
+| :-------------- | :------- | :------- | :------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [level](#level) | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-level.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/console/properties/level") |
+
+## level
+
+Minimum level of logs sent to this output
+
+`level`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-level.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/console/properties/level")
+
+### level Type
+
+`string`
+
+### level 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"`   |             |

+ 3 - 0
distributor-node/docs/schema/definition-properties-logs-properties-elasticsearch-logging-options-properties-endpoint.md

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

+ 60 - 0
distributor-node/docs/schema/definition-properties-logs-properties-elasticsearch-logging-options.md

@@ -0,0 +1,60 @@
+## elastic Type
+
+`object` ([Elasticsearch logging options](definition-properties-logs-properties-elasticsearch-logging-options.md))
+
+# elastic Properties
+
+| Property              | Type     | Required | Nullable       | Defined by                                                                                                                                                                                                                        |
+| :-------------------- | :------- | :------- | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [level](#level)       | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-level.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/elastic/properties/level")                |
+| [endpoint](#endpoint) | `string` | Required | cannot be null | [Distributor node configuration](definition-properties-logs-properties-elasticsearch-logging-options-properties-endpoint.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/elastic/properties/endpoint") |
+
+## level
+
+Minimum level of logs sent to this output
+
+`level`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-level.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/elastic/properties/level")
+
+### level Type
+
+`string`
+
+### level 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"`   |             |
+
+## endpoint
+
+Elastichsearch endpoint to push the logs to (for example: <http://localhost:9200>)
+
+`endpoint`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-elasticsearch-logging-options-properties-endpoint.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/elastic/properties/endpoint")
+
+### endpoint Type
+
+`string`

+ 3 - 0
distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-archive.md

@@ -0,0 +1,3 @@
+## archive Type
+
+`boolean`

+ 22 - 0
distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-frequency.md

@@ -0,0 +1,22 @@
+## frequency Type
+
+`string`
+
+## frequency Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"yearly"`  |             |
+| `"monthly"` |             |
+| `"daily"`   |             |
+| `"hourly"`  |             |
+
+## frequency Default Value
+
+The default value is:
+
+```json
+"daily"
+```

+ 17 - 0
distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-level.md

@@ -0,0 +1,17 @@
+## level Type
+
+`string`
+
+## level 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"`   |             |

+ 7 - 0
distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-maxfiles.md

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

+ 7 - 0
distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-maxsize.md

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

+ 3 - 0
distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options-properties-path.md

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

+ 163 - 0
distributor-node/docs/schema/definition-properties-logs-properties-file-logging-options.md

@@ -0,0 +1,163 @@
+## file Type
+
+`object` ([File logging options](definition-properties-logs-properties-file-logging-options.md))
+
+# file Properties
+
+| Property                | Type      | Required | Nullable       | Defined by                                                                                                                                                                                                              |
+| :---------------------- | :-------- | :------- | :------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [level](#level)         | `string`  | Required | cannot be null | [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-level.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/level")         |
+| [path](#path)           | `string`  | Required | cannot be null | [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-path.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/path")           |
+| [maxFiles](#maxfiles)   | `integer` | Optional | cannot be null | [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-maxfiles.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/maxFiles")   |
+| [maxSize](#maxsize)     | `integer` | Optional | cannot be null | [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-maxsize.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/maxSize")     |
+| [frequency](#frequency) | `string`  | Optional | cannot be null | [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-frequency.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/frequency") |
+| [archive](#archive)     | `boolean` | Optional | cannot be null | [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-archive.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/archive")     |
+
+## level
+
+Minimum level of logs sent to this output
+
+`level`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-level.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/level")
+
+### level Type
+
+`string`
+
+### level 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"`   |             |
+
+## path
+
+Path where the logs will be stored (absolute or relative to config file)
+
+`path`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-path.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/path")
+
+### path Type
+
+`string`
+
+## maxFiles
+
+Maximum number of log files to store. Recommended to be at least 7 when frequency is set to `daily` and at least 24 \* 7 when frequency is set to `hourly`
+
+`maxFiles`
+
+*   is optional
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-maxfiles.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/maxFiles")
+
+### maxFiles Type
+
+`integer`
+
+### maxFiles Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1`
+
+## maxSize
+
+Maximum size of a single log file in bytes
+
+`maxSize`
+
+*   is optional
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-maxsize.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/maxSize")
+
+### maxSize Type
+
+`integer`
+
+### maxSize Constraints
+
+**minimum**: the value of this number must greater than or equal to: `1024`
+
+## frequency
+
+The frequency of creating new log files (regardless of maxSize)
+
+`frequency`
+
+*   is optional
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-frequency.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/frequency")
+
+### frequency Type
+
+`string`
+
+### frequency Constraints
+
+**enum**: the value of this property must be equal to one of the following values:
+
+| Value       | Explanation |
+| :---------- | :---------- |
+| `"yearly"`  |             |
+| `"monthly"` |             |
+| `"daily"`   |             |
+| `"hourly"`  |             |
+
+### frequency Default Value
+
+The default value is:
+
+```json
+"daily"
+```
+
+## archive
+
+Whether to archive old logs
+
+`archive`
+
+*   is optional
+
+*   Type: `boolean`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-file-logging-options-properties-archive.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file/properties/archive")
+
+### archive Type
+
+`boolean`

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

@@ -0,0 +1,65 @@
+## logs Type
+
+`object` ([Details](definition-properties-logs.md))
+
+# logs Properties
+
+| Property            | Type     | Required | Nullable       | Defined by                                                                                                                                                                                |
+| :------------------ | :------- | :------- | :------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [file](#file)       | `object` | Optional | cannot be null | [Distributor node configuration](definition-properties-logs-properties-file-logging-options.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file")             |
+| [console](#console) | `object` | Optional | cannot be null | [Distributor node configuration](definition-properties-logs-properties-console-logging-options.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/console")       |
+| [elastic](#elastic) | `object` | Optional | cannot be null | [Distributor node configuration](definition-properties-logs-properties-elasticsearch-logging-options.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/elastic") |
+
+## file
+
+
+
+`file`
+
+*   is optional
+
+*   Type: `object` ([File logging options](definition-properties-logs-properties-file-logging-options.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-file-logging-options.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/file")
+
+### file Type
+
+`object` ([File logging options](definition-properties-logs-properties-file-logging-options.md))
+
+## console
+
+
+
+`console`
+
+*   is optional
+
+*   Type: `object` ([Console logging options](definition-properties-logs-properties-console-logging-options.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-console-logging-options.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/console")
+
+### console Type
+
+`object` ([Console logging options](definition-properties-logs-properties-console-logging-options.md))
+
+## elastic
+
+
+
+`elastic`
+
+*   is optional
+
+*   Type: `object` ([Elasticsearch logging options](definition-properties-logs-properties-elasticsearch-logging-options.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs-properties-elasticsearch-logging-options.md "https://joystream.org/schemas/argus/config#/properties/logs/properties/elastic")
+
+### elastic Type
+
+`object` ([Elasticsearch logging options](definition-properties-logs-properties-elasticsearch-logging-options.md))

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

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

+ 7 - 0
distributor-node/docs/schema/definition-properties-operatorapi-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`

+ 50 - 0
distributor-node/docs/schema/definition-properties-operatorapi.md

@@ -0,0 +1,50 @@
+## operatorApi Type
+
+`object` ([Details](definition-properties-operatorapi.md))
+
+# operatorApi Properties
+
+| Property                  | Type      | Required | Nullable       | Defined by                                                                                                                                                                              |
+| :------------------------ | :-------- | :------- | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [port](#port)             | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-operatorapi-properties-port.md "https://joystream.org/schemas/argus/config#/properties/operatorApi/properties/port")             |
+| [hmacSecret](#hmacsecret) | `string`  | Required | cannot be null | [Distributor node configuration](definition-properties-operatorapi-properties-hmacsecret.md "https://joystream.org/schemas/argus/config#/properties/operatorApi/properties/hmacSecret") |
+
+## port
+
+Distributor node operator api port
+
+`port`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-operatorapi-properties-port.md "https://joystream.org/schemas/argus/config#/properties/operatorApi/properties/port")
+
+### port Type
+
+`integer`
+
+### port Constraints
+
+**minimum**: the value of this number must greater than or equal to: `0`
+
+## hmacSecret
+
+HMAC (HS256) secret key used for JWT authorization
+
+`hmacSecret`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-operatorapi-properties-hmacsecret.md "https://joystream.org/schemas/argus/config#/properties/operatorApi/properties/hmacSecret")
+
+### hmacSecret Type
+
+`string`

+ 7 - 0
distributor-node/docs/schema/definition-properties-publicapi-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`

+ 31 - 0
distributor-node/docs/schema/definition-properties-publicapi.md

@@ -0,0 +1,31 @@
+## publicApi Type
+
+`object` ([Details](definition-properties-publicapi.md))
+
+# publicApi Properties
+
+| Property      | Type      | Required | Nullable       | Defined by                                                                                                                                                              |
+| :------------ | :-------- | :------- | :------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [port](#port) | `integer` | Required | cannot be null | [Distributor node configuration](definition-properties-publicapi-properties-port.md "https://joystream.org/schemas/argus/config#/properties/publicApi/properties/port") |
+
+## port
+
+Distributor node public api port
+
+`port`
+
+*   is required
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-publicapi-properties-port.md "https://joystream.org/schemas/argus/config#/properties/publicApi/properties/port")
+
+### 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`

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

@@ -0,0 +1,235 @@
+## Distributor node configuration Type
+
+`object` ([Distributor node configuration](definition.md))
+
+# Distributor node configuration Properties
+
+| Property                    | Type      | Required | Nullable       | Defined by                                                                                                                                          |
+| :-------------------------- | :-------- | :------- | :------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [id](#id)                   | `string`  | Required | cannot be null | [Distributor node configuration](definition-properties-id.md "https://joystream.org/schemas/argus/config#/properties/id")                           |
+| [endpoints](#endpoints)     | `object`  | Required | cannot be null | [Distributor node configuration](definition-properties-endpoints.md "https://joystream.org/schemas/argus/config#/properties/endpoints")             |
+| [directories](#directories) | `object`  | Required | cannot be null | [Distributor node configuration](definition-properties-directories.md "https://joystream.org/schemas/argus/config#/properties/directories")         |
+| [logs](#logs)               | `object`  | Optional | cannot be null | [Distributor node configuration](definition-properties-logs.md "https://joystream.org/schemas/argus/config#/properties/logs")                       |
+| [limits](#limits)           | `object`  | Required | cannot be null | [Distributor node configuration](definition-properties-limits.md "https://joystream.org/schemas/argus/config#/properties/limits")                   |
+| [intervals](#intervals)     | `object`  | Required | cannot be null | [Distributor node configuration](definition-properties-intervals.md "https://joystream.org/schemas/argus/config#/properties/intervals")             |
+| [publicApi](#publicapi)     | `object`  | Required | cannot be null | [Distributor node configuration](definition-properties-publicapi.md "https://joystream.org/schemas/argus/config#/properties/publicApi")             |
+| [operatorApi](#operatorapi) | `object`  | Optional | cannot be null | [Distributor node configuration](definition-properties-operatorapi.md "https://joystream.org/schemas/argus/config#/properties/operatorApi")         |
+| [keys](#keys)               | `array`   | Optional | cannot be null | [Distributor node configuration](definition-properties-keys.md "https://joystream.org/schemas/argus/config#/properties/keys")                       |
+| [buckets](#buckets)         | `array`   | Optional | cannot be null | [Distributor node configuration](definition-properties-distributed-buckets-ids.md "https://joystream.org/schemas/argus/config#/properties/buckets") |
+| [workerId](#workerid)       | `integer` | Optional | cannot be null | [Distributor node configuration](definition-properties-workerid.md "https://joystream.org/schemas/argus/config#/properties/workerId")               |
+
+## id
+
+Node identifier used when sending elasticsearch logs and exposed on /status endpoint
+
+`id`
+
+*   is required
+
+*   Type: `string`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-id.md "https://joystream.org/schemas/argus/config#/properties/id")
+
+### id Type
+
+`string`
+
+### id Constraints
+
+**minimum length**: the minimum number of characters for this string is: `1`
+
+## 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 "https://joystream.org/schemas/argus/config#/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 "https://joystream.org/schemas/argus/config#/properties/directories")
+
+### directories Type
+
+`object` ([Details](definition-properties-directories.md))
+
+## logs
+
+Specifies the logging configuration
+
+`logs`
+
+*   is optional
+
+*   Type: `object` ([Details](definition-properties-logs.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-logs.md "https://joystream.org/schemas/argus/config#/properties/logs")
+
+### logs Type
+
+`object` ([Details](definition-properties-logs.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 "https://joystream.org/schemas/argus/config#/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 "https://joystream.org/schemas/argus/config#/properties/intervals")
+
+### intervals Type
+
+`object` ([Details](definition-properties-intervals.md))
+
+## publicApi
+
+Public api configuration
+
+`publicApi`
+
+*   is required
+
+*   Type: `object` ([Details](definition-properties-publicapi.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-publicapi.md "https://joystream.org/schemas/argus/config#/properties/publicApi")
+
+### publicApi Type
+
+`object` ([Details](definition-properties-publicapi.md))
+
+## operatorApi
+
+Operator api configuration
+
+`operatorApi`
+
+*   is optional
+
+*   Type: `object` ([Details](definition-properties-operatorapi.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-operatorapi.md "https://joystream.org/schemas/argus/config#/properties/operatorApi")
+
+### operatorApi Type
+
+`object` ([Details](definition-properties-operatorapi.md))
+
+## keys
+
+Specifies the keys available within distributor node CLI.
+
+`keys`
+
+*   is optional
+
+*   Type: an array of merged types ([Details](definition-properties-keys-items.md))
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-keys.md "https://joystream.org/schemas/argus/config#/properties/keys")
+
+### keys Type
+
+an array of merged types ([Details](definition-properties-keys-items.md))
+
+### keys Constraints
+
+**minimum number of items**: the minimum number of items for this array is: `1`
+
+## buckets
+
+Set of bucket ids distributed by the node. If not specified, all buckets currently assigned to worker specified in `config.workerId` will be distributed. Expected bucket id format is: {familyId}:{bucketIndex}
+
+`buckets`
+
+*   is optional
+
+*   Type: `string[]`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-distributed-buckets-ids.md "https://joystream.org/schemas/argus/config#/properties/buckets")
+
+### buckets Type
+
+`string[]`
+
+### buckets Constraints
+
+**minimum number of items**: the minimum number of items for this array is: `1`
+
+**unique items**: all items in this array must be unique. Duplicates are not allowed.
+
+## workerId
+
+ID of the node operator (distribution working group worker)
+
+`workerId`
+
+*   is optional
+
+*   Type: `integer`
+
+*   cannot be null
+
+*   defined in: [Distributor node configuration](definition-properties-workerid.md "https://joystream.org/schemas/argus/config#/properties/workerId")
+
+### workerId Type
+
+`integer`
+
+### workerId Constraints
+
+**minimum**: the value of this number must greater than or equal to: `0`

+ 7 - 0
distributor-node/openapitools.json

@@ -0,0 +1,7 @@
+{
+  "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json",
+  "spaces": 2,
+  "generator-cli": {
+    "version": "5.2.0"
+  }
+}

+ 153 - 0
distributor-node/package.json

@@ -0,0 +1,153 @@
+{
+  "name": "@joystream/distributor-cli",
+  "description": "Joystream distributor node CLI",
+  "version": "0.1.0",
+  "author": "Joystream contributors",
+  "bin": {
+    "joystream-distributor": "./bin/run"
+  },
+  "bugs": "https://github.com/Joystream/joystream/issues",
+  "dependencies": {
+    "@joystream/types": "^0.17.0",
+    "@joystream/metadata-protobuf": "^1.0.0",
+    "@elastic/ecs-winston-format": "^1.1.0",
+    "@oclif/command": "^1",
+    "@oclif/config": "^1",
+    "@oclif/plugin-help": "^3",
+    "@apollo/client": "^3.2.5",
+    "graphql": "^14.7.0",
+    "winston": "^3.3.3",
+    "fast-safe-stringify": "^2.1.1",
+    "ajv": "^7",
+    "axios": "^0.21.1",
+    "cross-fetch": "^3.1.4",
+    "express": "^4.17.1",
+    "express-winston": "^4.1.0",
+    "express-openapi-validator": "^4.12.4",
+    "file-type": "^16.5.1",
+    "lodash": "^4.17.21",
+    "lru-cache": "^6.0.0",
+    "node-cleanup": "^2.1.2",
+    "proper-lockfile": "^4.1.2",
+    "read-chunk": "^3.2.0",
+    "send": "^0.17.1",
+    "tslib": "^1",
+    "yaml": "^1.10.2",
+    "queue": "^6.0.2",
+    "express-http-proxy": "^1.6.2",
+    "winston-elasticsearch": "^0.15.8",
+    "node-cache": "^5.1.2",
+    "cors": "^2.8.5",
+    "inquirer": "^8.1.2",
+    "multihashes": "^4.0.3",
+    "blake3": "^2.1.4",
+    "js-image-generator": "^1.0.3",
+    "url-join": "^4.0.1",
+    "@types/url-join": "^4.0.1",
+    "winston-daily-rotate-file": "^4.5.5",
+    "jsonwebtoken": "^8.5.1"
+  },
+  "devDependencies": {
+    "@graphql-codegen/cli": "^1.21.4",
+    "@graphql-codegen/import-types-preset": "^1.18.1",
+    "@graphql-codegen/typescript": "^1.22.0",
+    "@graphql-codegen/typescript-document-nodes": "^1.17.11",
+    "@graphql-codegen/typescript-operations": "^1.17.16",
+    "@oclif/dev-cli": "^1",
+    "@oclif/test": "^1",
+    "@openapitools/openapi-generator-cli": "^2.3.6",
+    "@types/chai": "^4",
+    "@types/mocha": "^5",
+    "@types/node": "^14",
+    "@types/node-cleanup": "^2.1.1",
+    "@types/express-http-proxy": "^1.6.2",
+    "@types/node-cache": "^4.2.5",
+    "@types/send": "^0.17.0",
+    "@types/inquirer": "^8.1.1",
+    "@types/cors": "^2.8.12",
+    "chai": "^4",
+    "globby": "^10",
+    "json-schema-to-typescript": "^10.1.4",
+    "mocha": "^5",
+    "nyc": "^14",
+    "openapi-typescript": "^4.0.2",
+    "ts-node": "^8",
+    "typescript": "^3.3",
+    "@adobe/jsonschema2md": "https://github.com/adobe/jsonschema2md",
+    "widdershins": "^4.0.1",
+    "markdown-magic": "^2.5.2"
+  },
+  "engines": {
+    "node": ">=14.16.1"
+  },
+  "volta": {
+    "node": "14.16.1",
+    "yarn": "1.22.15"
+  },
+  "files": [
+    "/bin",
+    "/lib",
+    "/npm-shrinkwrap.json",
+    "/oclif.manifest.json"
+  ],
+  "homepage": "https://github.com/Joystream/joystream",
+  "keywords": [
+    "oclif"
+  ],
+  "license": "GPL-3.0-only",
+  "main": "lib/index.js",
+  "oclif": {
+    "commands": "./lib/commands",
+    "bin": "joystream-distributor",
+    "plugins": [
+      "@oclif/plugin-help"
+    ],
+    "topics": {
+      "leader": {
+        "description": "Commands for performing Distribution Working Group leader on-chain duties (like setting distribution module limits and parameters, assigning bags and buckets etc.)"
+      },
+      "operator": {
+        "description": "Commands for performing node operator (Distribution Working Group worker) on-chain duties (like accepting bucket invitations, setting node metadata)"
+      },
+      "node": {
+        "description": "Commands for interacting with a running distributor node through OperatorApi"
+      },
+      "dev": {
+        "description":"Developer utility commands"
+      }
+    }
+  },
+  "repository": {
+    "type": "git",
+    "url": "https://github.com/Joystream/joystream",
+    "directory": "distributor-node"
+  },
+  "scripts": {
+    "postpack": "rm -f oclif.manifest.json",
+    "prepack": "rm -rf lib && tsc -b && oclif-dev manifest && generate:all",
+    "test": "nyc --extension .ts mocha --forbid-only \"test/**/*.test.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:public-api": "yarn openapi-typescript ./src/api-spec/public.yml -o ./src/types/generated/PublicApi.ts -c ../prettierrc.js",
+    "generate:types:operator-api": "yarn openapi-typescript ./src/api-spec/operator.yml -o ./src/types/generated/OperatorApi.ts -c ../prettierrc.js",
+    "generate:types:api": "yarn generate:types:public-api && yarn generate:types:operator-api",
+    "generate:types:all": "yarn generate:types:json-schema && yarn generate:types:graphql && yarn generate:types:api",
+    "generate:api:storage-node": "yarn openapi-generator-cli generate -i ../storage-node/src/api-spec/openapi.yaml -g typescript-axios -o ./src/services/networking/storage-node/generated",
+    "generate:api:all": "yarn generate:api:storage-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:public-api": "yarn widdershins ./src/api-spec/public.yml --language_tabs javascript:JavaScript shell:Shell -o ./docs/api/public/index.md -u ./docs/api/templates",
+    "generate:docs:operator-api": "yarn widdershins ./src/api-spec/operator.yml --language_tabs javascript:JavaScript shell:Shell -o ./docs/api/operator/index.md -u ./docs/api/templates",
+    "generate:docs:api": "yarn generate:docs:public-api && yarn generate:docs:operator-api",
+    "generate:docs:toc": "yarn md-magic --path ./docs/**/*.md",
+    "generate:docs:all": "yarn generate:docs:cli && yarn generate:docs:config && yarn generate:docs:api && yarn generate:docs:toc",
+    "generate:all": "yarn generate:types:all && yarn generate:api:all && yarn generate:docs:all",
+    "build": "rm -rf lib && tsc --build tsconfig.json && cp -r ./src/api-spec ./lib/api-spec",
+    "lint": "eslint ./src --ext .ts",
+    "format": "prettier ./ --write",
+    "checks": "tsc --noEmit --pretty && prettier ./ --check && yarn lint",
+    "cli": "./bin/run"
+  },
+  "types": "lib/index.d.ts"
+}

+ 15 - 0
distributor-node/scripts/data/family-metadata.json

@@ -0,0 +1,15 @@
+{
+  "region": "eu-west",
+  "description": "Western Europe",
+  "areas": [
+    { "countryCode": "AT" },
+    { "countryCode": "BE" },
+    { "countryCode": "FR" },
+    { "countryCode": "DE" },
+    { "countryCode": "LI" },
+    { "countryCode": "LU" },
+    { "countryCode": "MC" },
+    { "countryCode": "NL" },
+    { "countryCode": "CH" }
+  ]
+}

+ 12 - 0
distributor-node/scripts/data/operator-metadata.json

@@ -0,0 +1,12 @@
+{
+  "endpoint": "http://localhost:3334",
+  "location": {
+    "countryCode": "DE",
+    "city": "Berlin",
+    "coordinates": {
+      "latitude": 52.520008,
+      "longitude": 13.404954
+    }
+  },
+  "extra": "Some additional information"
+}

+ 21 - 0
distributor-node/scripts/init-bucket.sh

@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+
+SCRIPT_PATH="$(dirname "${BASH_SOURCE[0]}")"
+cd $SCRIPT_PATH
+
+export AUTO_CONFIRM=true
+export CONFIG_PATH="../config.yml"
+CLI=../bin/run
+
+${CLI} dev:init
+${CLI} leader:set-buckets-per-bag-limit -l 10
+FAMILY_ID=`${CLI} leader:create-bucket-family ${CONFIG}`
+BUCKET_INDEX=`${CLI} leader:create-bucket -f ${FAMILY_ID} -a yes`
+BUCKET_ID="${FAMILY_ID}:${BUCKET_INDEX}"
+${CLI} leader:update-bag -b static:council -f ${FAMILY_ID} -a ${BUCKET_INDEX}
+${CLI} leader:update-bucket-mode -B ${BUCKET_ID} --mode on
+${CLI} leader:invite-bucket-operator -B ${BUCKET_ID} -w 0
+${CLI} operator:accept-invitation -B ${BUCKET_ID} -w 0
+${CLI} operator:set-metadata -B ${BUCKET_ID} -w 0 -e http://localhost:3334
+${CLI} leader:update-dynamic-bag-policy -t Channel -p ${FAMILY_ID}:1
+${CLI} leader:update-dynamic-bag-policy -t Member -p ${FAMILY_ID}:1

+ 57 - 0
distributor-node/scripts/test-commands.sh

@@ -0,0 +1,57 @@
+#!/usr/bin/env bash
+
+SCRIPT_PATH="$(dirname "${BASH_SOURCE[0]}")"
+cd $SCRIPT_PATH
+
+export AUTO_CONFIRM=true
+export CONFIG_PATH="../config.yml"
+CLI=../bin/run
+
+${CLI} dev:init
+${CLI} leader:set-buckets-per-bag-limit -l 10
+# Create family and buckets
+FAMILY_ID=`${CLI} leader:create-bucket-family`
+BUCKET_1_INDEX=`${CLI} leader:create-bucket -f ${FAMILY_ID} -a yes`
+BUCKET_2_INDEX=`${CLI} leader:create-bucket -f ${FAMILY_ID} -a yes`
+BUCKET_1_ID="${FAMILY_ID}:${BUCKET_1_INDEX}"
+BUCKET_2_ID="${FAMILY_ID}:${BUCKET_2_INDEX}"
+# Test adding 2 buckets to bag at once
+${CLI} leader:update-bag -b static:council -f ${FAMILY_ID} -a ${BUCKET_1_INDEX} ${BUCKET_2_INDEX}
+# Test removing 2 buckets from bag at once
+${CLI} leader:update-bag -b static:council -f ${FAMILY_ID} -r ${BUCKET_1_INDEX} ${BUCKET_2_INDEX}
+# Adding single bucket to all static bags
+${CLI} leader:update-bag -b static:council -f ${FAMILY_ID} -a ${BUCKET_1_INDEX}
+${CLI} leader:update-bag -b static:wg:storage -f ${FAMILY_ID} -a ${BUCKET_1_INDEX}
+${CLI} leader:update-bag -b static:wg:content -f ${FAMILY_ID} -a ${BUCKET_1_INDEX}
+${CLI} leader:update-bag -b static:wg:operationsAlpha -f ${FAMILY_ID} -a ${BUCKET_1_INDEX}
+${CLI} leader:update-bag -b static:wg:operationsBeta -f ${FAMILY_ID} -a ${BUCKET_1_INDEX}
+${CLI} leader:update-bag -b static:wg:operationsGamma -f ${FAMILY_ID} -a ${BUCKET_1_INDEX}
+${CLI} leader:update-bag -b static:wg:gateway -f ${FAMILY_ID} -a ${BUCKET_1_INDEX}
+${CLI} leader:update-bag -b static:wg:distribution -f ${FAMILY_ID} -a ${BUCKET_1_INDEX}
+# Update bucket status / mode
+${CLI} leader:update-bucket-status -B ${BUCKET_1_ID}  --acceptingBags yes
+${CLI} leader:update-bucket-mode -B ${BUCKET_1_ID} --mode on
+${CLI} leader:update-bucket-status -B ${BUCKET_2_ID}  --acceptingBags no
+${CLI} leader:update-bucket-mode -B ${BUCKET_2_ID} --mode off
+# Update dynamic bag policies
+${CLI} leader:update-dynamic-bag-policy -t Channel -p ${FAMILY_ID}:5
+${CLI} leader:update-dynamic-bag-policy -t Member -p ${FAMILY_ID}:5
+${CLI} leader:update-dynamic-bag-policy -t Member
+# Bucket invitations + cancelling and accepting
+${CLI} leader:invite-bucket-operator -B ${BUCKET_1_ID} -w 0
+${CLI} leader:invite-bucket-operator -B ${BUCKET_2_ID} -w 0
+${CLI} operator:accept-invitation -B ${BUCKET_1_ID} -w 0
+${CLI} leader:cancel-invitation -B ${BUCKET_2_ID} -w 0
+# Setting metadata
+${CLI} operator:set-metadata -B ${BUCKET_1_ID} -w 0 -i ./data/operator-metadata.json
+${CLI} leader:set-bucket-family-metadata -f ${FAMILY_ID} -i ./data/family-metadata.json
+
+# Deletion commands tested separately
+FAMILY_TO_DELETE_ID=`${CLI} leader:create-bucket-family`
+BUCKET_TO_DELETE_INDEX=`${CLI} leader:create-bucket -f ${FAMILY_TO_DELETE_ID} -a yes`
+BUCKET_TO_DELETE_ID="${FAMILY_TO_DELETE_ID}:${BUCKET_TO_DELETE_INDEX}"
+${CLI} leader:invite-bucket-operator -B ${BUCKET_TO_DELETE_ID} -w 0
+${CLI} operator:accept-invitation -B ${BUCKET_TO_DELETE_ID} -w 0
+${CLI} leader:remove-bucket-operator -B ${BUCKET_TO_DELETE_ID} -w 0
+${CLI} leader:delete-bucket -B ${BUCKET_TO_DELETE_ID}
+${CLI} leader:delete-bucket-family -f ${FAMILY_TO_DELETE_ID}

+ 1 - 0
distributor-node/src/@types/@elastic/esc-winston-format/index.d.ts

@@ -0,0 +1 @@
+declare module '@elastic/ecs-winston-format'

+ 1 - 0
distributor-node/src/@types/js-image-generator/index.d.ts

@@ -0,0 +1 @@
+declare module 'js-image-generator'

+ 119 - 0
distributor-node/src/api-spec/operator.yml

@@ -0,0 +1,119 @@
+openapi: 3.0.3
+info:
+  title: Distributor node operator API
+  description: Distributor node operator API
+  contact:
+    email: info@joystream.org
+  license:
+    name: GPL-3.0-only
+    url: https://spdx.org/licenses/GPL-3.0-only.html
+  version: 0.1.0
+servers:
+  - url: http://localhost:3335/api/v1/
+
+paths:
+  /stop-api:
+    post:
+      operationId: operator.stopApi
+      description: Turns off the public api.
+      responses:
+        200:
+          description: OK
+        401:
+          description: Not authorized
+        409:
+          description: Already stopped
+        500:
+          description: Unexpected server error
+  /start-api:
+    post:
+      operationId: operator.startApi
+      description: Turns on the public api.
+      responses:
+        200:
+          description: OK
+        401:
+          description: Not authorized
+        409:
+          description: Already started
+        500:
+          description: Unexpected server error
+  /shutdown:
+    post:
+      operationId: operator.shutdown
+      description: Shuts down the node.
+      responses:
+        200:
+          description: OK
+        401:
+          description: Not authorized
+        409:
+          description: Already shutting down
+        500:
+          description: Unexpected server error
+  /set-worker:
+    post:
+      operationId: operator.setWorker
+      description: Updates the operator worker id.
+      requestBody:
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/SetWorkerOperation'
+      responses:
+        200:
+          description: OK
+        401:
+          description: Not authorized
+        500:
+          description: Unexpected server error
+  /set-buckets:
+    post:
+      operationId: operator.setBuckets
+      description: Updates buckets supported by the node.
+      requestBody:
+        content:
+          application/json:
+            schema:
+              $ref: '#/components/schemas/SetBucketsOperation'
+      responses:
+        200:
+          description: OK
+        401:
+          description: Not authorized
+        500:
+          description: Unexpected server error
+
+components:
+  securitySchemes:
+    OperatorAuth:
+      type: http
+      scheme: bearer
+      bearerFormat:
+        "JWT signed with HMAC (HS256) secret key specified in distributor node's `config.operator.hmacSecret`.
+        The payload should include:
+        - `reqBody` - content of the request body
+        - `reqUrl` - request url (only pathname + query string, without origin. For example: `/api/v1/set-buckets`)"
+  schemas:
+    SetWorkerOperation:
+      type: object
+      required:
+        - workerId
+      properties:
+        workerId:
+          type: integer
+          minimum: 0
+    SetBucketsOperation:
+      type: object
+      properties:
+        buckets:
+          description: 'Set of bucket ids to be distributed by the node.
+            If not provided - all buckets assigned to currently configured worker will be distributed.'
+          type: array
+          minItems: 1
+          items:
+            type: string
+            pattern: ^[0-9]+:[0-9]+$
+
+security:
+  - OperatorAuth: []

+ 203 - 0
distributor-node/src/api-spec/public.yml

@@ -0,0 +1,203 @@
+openapi: 3.0.3
+info:
+  title: Distributor node public API
+  description: Distributor node public API
+  contact:
+    email: info@joystream.org
+  license:
+    name: GPL-3.0-only
+    url: https://spdx.org/licenses/GPL-3.0-only.html
+  version: 0.1.0
+externalDocs:
+  description: Distributor node public API
+  url: https://github.com/Joystream/joystream/issues/2224
+servers:
+  - url: http://localhost:3334/api/v1/
+
+paths:
+  /status:
+    get:
+      operationId: public.status
+      description: Returns json object describing current node status.
+      responses:
+        200:
+          description: OK
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/StatusResponse'
+        500:
+          description: Unexpected server error
+  /buckets:
+    get:
+      operationId: public.buckets
+      description: Returns list of distributed buckets
+      responses:
+        200:
+          description: OK
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/BucketsResponse'
+        500:
+          description: Unexpected server error
+  /assets/{objectId}:
+    head:
+      operationId: public.assetHead
+      description: Returns asset response headers (cache status, content type and/or length, accepted ranges etc.)
+      parameters:
+        - $ref: '#/components/parameters/ObjectId'
+      responses:
+        200:
+          description: Object is supported and should be send on GET request.
+          headers:
+            X-Cache:
+              $ref: '#/components/headers/X-Cache'
+        421:
+          description: Misdirected request. Data object not supported by the node.
+        404:
+          description: Data object does not exist.
+        500:
+          description: Unexpected server error
+    get:
+      operationId: public.asset
+      description: Returns a media file.
+      parameters:
+        - $ref: '#/components/parameters/ObjectId'
+      responses:
+        200:
+          description: Full available object data sent
+          headers:
+            X-Cache:
+              $ref: '#/components/headers/X-Cache'
+            X-Data-Source:
+              $ref: '#/components/headers/X-Data-Source'
+          content:
+            image/*:
+              schema:
+                type: string
+                format: binary
+            audio/*:
+              schema:
+                type: string
+                format: binary
+            video/*:
+              schema:
+                type: string
+                format: binary
+        206:
+          description: Requested partial object data sent
+          headers:
+            X-Cache:
+              $ref: '#/components/headers/X-Cache'
+            X-Data-Source:
+              $ref: '#/components/headers/X-Data-Source'
+          content:
+            image/*:
+              schema:
+                type: string
+                format: binary
+            audio/*:
+              schema:
+                type: string
+                format: binary
+            video/*:
+              schema:
+                type: string
+                format: binary
+        421:
+          description: Misdirected request. Data object not supported.
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/ErrorResponse'
+        404:
+          description: Data object does not exist.
+          content:
+            application/json:
+              schema:
+                $ref: '#/components/schemas/ErrorResponse'
+        500:
+          description: Unexpected server error
+
+components:
+  parameters:
+    ObjectId:
+      name: objectId
+      required: true
+      in: path
+      description: Data Object ID
+      schema:
+        type: string
+        pattern: \d+
+  headers:
+    X-Cache:
+      description: 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.
+      schema:
+        type: string
+        enum: ['hit', 'pending', 'miss']
+    X-Data-Source:
+      description: Describes the source of data stream.
+        External - the request was proxied to a storage node.
+        Local - the data is streamed from local file.
+      schema:
+        type: string
+        enum: ['external', 'local']
+  schemas:
+    ErrorResponse:
+      type: object
+      required:
+        - message
+      properties:
+        type:
+          type: string
+        message:
+          type: string
+    StatusResponse:
+      type: object
+      required:
+        - id
+        - objectsInCache
+        - storageLimit
+        - storageUsed
+        - uptime
+        - downloadsInProgress
+      properties:
+        id:
+          type: string
+        objectsInCache:
+          type: integer
+          minimum: 0
+        storageLimit:
+          type: integer
+          minimum: 0
+        storageUsed:
+          type: integer
+          minimum: 0
+        uptime:
+          type: integer
+          minimum: 0
+        downloadsInProgress:
+          type: integer
+          minimum: 0
+    BucketsResponse:
+      oneOf:
+        - type: object
+          required:
+            - 'bucketIds'
+          properties:
+            bucketIds:
+              type: array
+              items:
+                type: string
+                pattern: ^[0-9]+:[0-9]+$
+        - type: object
+          required:
+            - 'allByWorkerId'
+          properties:
+            allByWorkerId:
+              type: integer
+              minimum: 0

+ 180 - 0
distributor-node/src/app/index.ts

@@ -0,0 +1,180 @@
+import { Config } from '../types'
+import { NetworkingService } from '../services/networking'
+import { LoggingService } from '../services/logging'
+import { StateCacheService } from '../services/cache/StateCacheService'
+import { ContentService } from '../services/content/ContentService'
+import { Logger } from 'winston'
+import fs from 'fs'
+import nodeCleanup from 'node-cleanup'
+import { AppIntervals } from '../types/app'
+import { PublicApiService } from '../services/httpApi/PublicApiService'
+import { OperatorApiService } from '../services/httpApi/OperatorApiService'
+
+export class App {
+  private config: Config
+  private content: ContentService
+  private stateCache: StateCacheService
+  private networking: NetworkingService
+  private publicApi: PublicApiService
+  private operatorApi: OperatorApiService | undefined
+  private logging: LoggingService
+  private logger: Logger
+  private intervals: AppIntervals | undefined
+  private isStopping = false
+
+  constructor(config: Config) {
+    this.config = config
+    this.logging = LoggingService.withAppConfig(config)
+    this.stateCache = new StateCacheService(config, this.logging)
+    this.networking = new NetworkingService(config, this.stateCache, this.logging)
+    this.content = new ContentService(config, this.logging, this.networking, this.stateCache)
+    this.publicApi = new PublicApiService(config, this.stateCache, this.content, this.logging, this.networking)
+    if (this.config.operatorApi) {
+      this.operatorApi = new OperatorApiService(config, this, this.logging, this.publicApi)
+    }
+    this.logger = this.logging.createLogger('App')
+  }
+
+  private setIntervals() {
+    this.intervals = {
+      saveCacheState: setInterval(() => this.stateCache.save(), this.config.intervals.saveCacheState * 1000),
+      checkStorageNodeResponseTimes: setInterval(
+        () => this.networking.checkActiveStorageNodeEndpoints(),
+        this.config.intervals.checkStorageNodeResponseTimes * 1000
+      ),
+      cacheCleanup: setInterval(() => this.content.cacheCleanup(), this.config.intervals.cacheCleanup * 1000),
+    }
+  }
+
+  private clearIntervals() {
+    if (this.intervals) {
+      Object.values(this.intervals).forEach((interval) => clearInterval(interval))
+    }
+  }
+
+  private checkConfigDir(name: string, path: string): void {
+    const dirInfo = `${name} directory (${path})`
+    if (!fs.existsSync(path)) {
+      try {
+        fs.mkdirSync(path, { recursive: true })
+      } catch (e) {
+        throw new Error(`${dirInfo} doesn't exist and cannot be created!`)
+      }
+    }
+    try {
+      fs.accessSync(path, fs.constants.R_OK)
+    } catch (e) {
+      throw new Error(`${dirInfo} is not readable`)
+    }
+    try {
+      fs.accessSync(path, fs.constants.W_OK)
+    } catch (e) {
+      throw new Error(`${dirInfo} is not writable`)
+    }
+  }
+
+  private checkConfigDirectories(): void {
+    Object.entries(this.config.directories).forEach(([name, path]) => this.checkConfigDir(name, path))
+    if (this.config.logs?.file) {
+      this.checkConfigDir('logs.file.path', this.config.logs.file.path)
+    }
+  }
+
+  public async start(): Promise<void> {
+    this.logger.info('Starting the app', { config: this.config })
+    try {
+      this.checkConfigDirectories()
+      this.stateCache.load()
+      await this.content.startupInit()
+      this.setIntervals()
+      this.publicApi.start()
+      this.operatorApi?.start()
+    } catch (err) {
+      this.logger.error('Node initialization failed!', { err })
+      process.exit(-1)
+    }
+    nodeCleanup(this.exitHandler.bind(this))
+  }
+
+  public stop(timeoutSec?: number): boolean {
+    if (this.isStopping) {
+      return false
+    }
+    this.logger.info(`Stopping the app${timeoutSec ? ` in ${timeoutSec} sec...` : ''}`)
+    this.isStopping = true
+    if (timeoutSec) {
+      setTimeout(() => process.kill(process.pid, 'SIGINT'), timeoutSec * 1000)
+    } else {
+      process.kill(process.pid, 'SIGINT')
+    }
+
+    return true
+  }
+
+  private async exitGracefully(): Promise<void> {
+    // Async exit handler - ideally should not take more than 10 sec
+    // We can try to wait until some pending downloads are finished here etc.
+    this.logger.info('Graceful exit initialized')
+
+    // Try to process remaining downloads
+    const MAX_RETRY_ATTEMPTS = 3
+    let retryCounter = 0
+    while (retryCounter < MAX_RETRY_ATTEMPTS && this.stateCache.getPendingDownloadsCount()) {
+      const pendingDownloadsCount = this.stateCache.getPendingDownloadsCount()
+      this.logger.info(`${pendingDownloadsCount} pending downloads in progress... Retrying exit in 5 sec...`, {
+        retryCounter,
+        pendingDownloadsCount,
+      })
+      await new Promise((resolve) => setTimeout(resolve, 5000))
+      this.stateCache.saveSync()
+      ++retryCounter
+    }
+
+    if (this.stateCache.getPendingDownloadsCount()) {
+      this.logger.warn('Limit reached: Could not finish all pending downloads.', {
+        pendingDownloadsCount: this.stateCache.getPendingDownloadsCount(),
+      })
+    }
+
+    this.logger.info('Graceful exit finished')
+    await this.logging.end()
+  }
+
+  private exitCritically(): void {
+    // Some additional synchronous work if required...
+    this.logger.info('Critical exit finished')
+  }
+
+  private exitHandler(exitCode: number | null, signal: string | null): boolean | undefined {
+    this.logger.info('Exiting...')
+    // Clear intervals
+    this.clearIntervals()
+    // Stop the http apis
+    this.publicApi.stop()
+    this.operatorApi?.stop()
+    // Save cache
+    try {
+      this.stateCache.saveSync()
+    } catch (err) {
+      this.logger.error('Failed to save the cache state on exit!', { err })
+    }
+    if (signal) {
+      // Async exit can be executed
+      this.exitGracefully()
+        .then(() => {
+          process.kill(process.pid, signal)
+        })
+        .catch((err) => {
+          this.logger.error('Graceful exit error', { err })
+          this.logging.end().finally(() => {
+            process.kill(process.pid, signal)
+          })
+        })
+      nodeCleanup.uninstall()
+      return false
+    } else {
+      // Only synchronous work can be done here
+      this.exitCritically()
+    }
+  }
+}

+ 9 - 0
distributor-node/src/command-base/ExitCodes.ts

@@ -0,0 +1,9 @@
+enum ExitCodes {
+  OK = 0,
+  Error = 1,
+  ApiError = 200,
+  InvalidInput = 400,
+  FileNotFound = 401,
+  InvalidFile = 402,
+}
+export = ExitCodes

+ 162 - 0
distributor-node/src/command-base/accounts.ts

@@ -0,0 +1,162 @@
+import ApiCommandBase from './api'
+import { AccountId } from '@polkadot/types/interfaces'
+import { Keyring } from '@polkadot/api'
+import { KeyringInstance, KeyringOptions, KeyringPair, KeyringPair$Json } from '@polkadot/keyring/types'
+import { CLIError } from '@oclif/errors'
+import ExitCodes from './ExitCodes'
+import fs from 'fs'
+import path from 'path'
+import inquirer from 'inquirer'
+
+export const DEFAULT_ACCOUNT_TYPE = 'sr25519'
+export const KEYRING_OPTIONS: KeyringOptions = {
+  type: DEFAULT_ACCOUNT_TYPE,
+}
+
+/**
+ * Abstract base class for account-related commands.
+ */
+export default abstract class AccountsCommandBase extends ApiCommandBase {
+  private keyring!: KeyringInstance
+
+  fetchAccountFromJsonFile(jsonBackupFilePath: string): KeyringPair {
+    if (!fs.existsSync(jsonBackupFilePath)) {
+      throw new CLIError(`Keypair backup json file does not exist: ${jsonBackupFilePath}`, {
+        exit: ExitCodes.FileNotFound,
+      })
+    }
+    if (path.extname(jsonBackupFilePath) !== '.json') {
+      throw new CLIError(`Keypair backup json file is invalid: File extension should be .json: ${jsonBackupFilePath}`, {
+        exit: ExitCodes.InvalidFile,
+      })
+    }
+    let accountJsonObj: unknown
+    try {
+      accountJsonObj = require(jsonBackupFilePath)
+    } catch (e) {
+      throw new CLIError(`Keypair backup json file is invalid or cannot be accessed: ${jsonBackupFilePath}`, {
+        exit: ExitCodes.InvalidFile,
+      })
+    }
+    if (typeof accountJsonObj !== 'object' || accountJsonObj === null) {
+      throw new CLIError(`Keypair backup json file is is not valid: ${jsonBackupFilePath}`, {
+        exit: ExitCodes.InvalidFile,
+      })
+    }
+
+    const keyring = new Keyring()
+    let account: KeyringPair
+    try {
+      // Try adding and retrieving the keys in order to validate that the backup file is correct
+      keyring.addFromJson(accountJsonObj as KeyringPair$Json)
+      account = keyring.getPair((accountJsonObj as KeyringPair$Json).address)
+    } catch (e) {
+      throw new CLIError(`Keypair backup json file is is not valid: ${jsonBackupFilePath}`, {
+        exit: ExitCodes.InvalidFile,
+      })
+    }
+
+    return account
+  }
+
+  isKeyAvailable(key: AccountId | string): boolean {
+    return this.keyring.getPairs().some((p) => p.address === key.toString())
+  }
+
+  getPairs(includeDevAccounts = true): KeyringPair[] {
+    return this.keyring.getPairs().filter((p) => includeDevAccounts || !p.meta.isTesting)
+  }
+
+  getPair(key: string): KeyringPair {
+    const pair = this.keyring.getPair(key)
+    if (!pair) {
+      throw new CLIError(`Required key for account ${key} is not available`)
+    }
+    return pair
+  }
+
+  async getDecodedPair(key: string): Promise<KeyringPair> {
+    const pair = this.getPair(key)
+    return this.requestPairDecoding(pair)
+  }
+
+  async requestPairDecoding(pair: KeyringPair, message?: string): Promise<KeyringPair> {
+    // Skip if pair already unlocked
+    if (!pair.isLocked) {
+      return pair
+    }
+
+    // Try decoding using empty string
+    try {
+      pair.decodePkcs8('')
+      return pair
+    } catch (e) {
+      // Continue...
+    }
+
+    let isPassValid = false
+    while (!isPassValid) {
+      try {
+        const password = await this.promptForPassword(
+          message || `Enter ${pair.meta.name ? pair.meta.name : pair.address} account password`
+        )
+        pair.decodePkcs8(password)
+        isPassValid = true
+      } catch (e) {
+        this.warn('Invalid password... Try again.')
+      }
+    }
+
+    return pair
+  }
+
+  async promptForPassword(message = "Your account's password"): Promise<string> {
+    const { password } = await inquirer.prompt([
+      {
+        name: 'password',
+        type: 'password',
+        message,
+      },
+    ])
+
+    return password
+  }
+
+  initKeyring(): void {
+    this.keyring = new Keyring(KEYRING_OPTIONS)
+    this.appConfig.keys?.forEach((keyData) => {
+      if ('suri' in keyData) {
+        this.keyring.addFromUri(keyData.suri, undefined, keyData.type)
+      }
+      if ('mnemonic' in keyData) {
+        this.keyring.addFromMnemonic(keyData.mnemonic, undefined, keyData.type)
+      }
+      if ('keyfile' in keyData) {
+        const acc = this.fetchAccountFromJsonFile(keyData.keyfile)
+        this.keyring.addPair(acc)
+      }
+    })
+  }
+
+  async getDistributorLeadKey(): Promise<string> {
+    const currentLead = await this.api.query.distributionWorkingGroup.currentLead()
+    if (!currentLead.isSome) {
+      throw new CLIError('There is no active distributor working group lead currently')
+    }
+    const worker = await this.api.query.distributionWorkingGroup.workerById(currentLead.unwrap())
+    return worker.role_account_id.toString()
+  }
+
+  async getDistributorWorkerRoleKey(workerId: number): Promise<string> {
+    const worker = await this.api.query.distributionWorkingGroup.workerById(workerId)
+    if (!worker) {
+      throw new CLIError(`Worker not found by id: ${workerId}!`)
+    }
+    return worker.role_account_id.toString()
+  }
+
+  async init(): Promise<void> {
+    await super.init()
+    await this.initKeyring()
+  }
+}

+ 40 - 0
distributor-node/src/command-base/api.ts

@@ -0,0 +1,40 @@
+import DefaultCommandBase from './default'
+import { CLIError } from '@oclif/errors'
+import { SubmittableResult } from '@polkadot/api'
+import { KeyringPair } from '@polkadot/keyring/types'
+import chalk from 'chalk'
+import { SubmittableExtrinsic } from '@polkadot/api/types'
+import { formatBalance } from '@polkadot/util'
+import { ExtrinsicFailedError, RuntimeApi } from '../services/networking/runtime/api'
+import ExitCodes from './ExitCodes'
+
+/**
+ * Abstract base class for commands that require access to the API.
+ */
+export default abstract class ApiCommandBase extends DefaultCommandBase {
+  protected api!: RuntimeApi
+
+  async init(): Promise<void> {
+    await super.init()
+    this.api = await RuntimeApi.create(this.logging, this.appConfig.endpoints.joystreamNodeWs)
+  }
+
+  async sendAndFollowTx(account: KeyringPair, tx: SubmittableExtrinsic<'promise'>): Promise<SubmittableResult> {
+    // Calculate fee and ask for confirmation
+    const fee = await this.api.estimateFee(account, tx)
+
+    await this.requireConfirmation(
+      `Tx fee of ${chalk.cyan(formatBalance(fee))} will be deduced from you account, do you confirm the transfer?`
+    )
+
+    try {
+      const res = await this.api.sendExtrinsic(account, tx)
+      return res
+    } catch (e) {
+      if (e instanceof ExtrinsicFailedError) {
+        throw new CLIError(`Extrinsic failed! ${e.message}`, { exit: ExitCodes.ApiError })
+      }
+      throw e
+    }
+  }
+}

+ 108 - 0
distributor-node/src/command-base/default.ts

@@ -0,0 +1,108 @@
+import Command, { flags as oclifFlags } from '@oclif/command'
+import inquirer from 'inquirer'
+import ExitCodes from './ExitCodes'
+import { ReadonlyConfig } from '../types/config'
+import { ConfigParserService } from '../services/parsers/ConfigParserService'
+import { LoggingService } from '../services/logging'
+import { Logger } from 'winston'
+import { BagIdParserService } from '../services/parsers/BagIdParserService'
+import { BucketIdParserService } from '../services/parsers/BucketIdParserService'
+
+export const flags = {
+  ...oclifFlags,
+  integerArr: oclifFlags.build({
+    parse: (value: string) => {
+      const arr: number[] = value.split(',').map((v) => {
+        if (!/^-?\d+$/.test(v)) {
+          throw new Error(`Expected comma-separated integers, but received: ${value}`)
+        }
+        return parseInt(v)
+      })
+      return arr
+    },
+  }),
+  bagId: oclifFlags.build({
+    char: 'b',
+    parse: (value: string) => {
+      const parser = new BagIdParserService(value)
+      return parser.parse()
+    },
+    description: `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`,
+  }),
+  bucketId: oclifFlags.build({
+    char: 'B',
+    parse: (value: string) => {
+      return BucketIdParserService.parseBucketId(value)
+    },
+    description: `Distribution bucket ID in {familyId}:{bucketIndex} format.`,
+  }),
+}
+export default abstract class DefaultCommandBase extends Command {
+  protected appConfig!: ReadonlyConfig
+  protected logging!: LoggingService
+  protected autoConfirm!: boolean
+  private logger!: Logger
+
+  static flags = {
+    yes: flags.boolean({
+      required: false,
+      default: false,
+      description: 'Answer "yes" to any prompt, skipping any manual confirmations',
+      char: 'y',
+    }),
+    configPath: flags.string({
+      required: false,
+      default: process.env.CONFIG_PATH || './config.yml',
+      description: 'Path to config JSON/YAML file (relative to current working directory)',
+      char: 'c',
+    }),
+  }
+
+  async init(): Promise<void> {
+    const { configPath, yes } = this.parse(this.constructor as typeof DefaultCommandBase).flags
+    const configParser = new ConfigParserService(configPath)
+    this.appConfig = configParser.parse() as ReadonlyConfig
+    this.logging = LoggingService.withCLIConfig()
+    this.logger = this.logging.createLogger('CLI')
+    this.autoConfirm = !!(process.env.AUTO_CONFIRM === 'true' || parseInt(process.env.AUTO_CONFIRM || '') || yes)
+  }
+
+  public log(message: string, ...meta: unknown[]): void {
+    this.logger.info(message, ...meta)
+  }
+
+  public output(value: unknown): void {
+    console.log(value)
+  }
+
+  async requireConfirmation(
+    message = 'Are you sure you want to execute this action?',
+    defaultVal = false
+  ): Promise<void> {
+    if (this.autoConfirm) {
+      return
+    }
+    const { confirmed } = await inquirer.prompt([{ type: 'confirm', name: 'confirmed', message, default: defaultVal }])
+    if (!confirmed) {
+      this.exit(ExitCodes.OK)
+    }
+  }
+
+  async finally(err: unknown): Promise<void> {
+    if (!err) this.exit(ExitCodes.OK)
+    if (process.env.DEBUG === 'true') {
+      console.error(err)
+    }
+    super.finally(err as Error)
+  }
+}

+ 58 - 0
distributor-node/src/command-base/node.ts

@@ -0,0 +1,58 @@
+import axios from 'axios'
+import urljoin from 'url-join'
+import DefaultCommandBase, { flags } from './default'
+import jwt from 'jsonwebtoken'
+import ExitCodes from './ExitCodes'
+
+export default abstract class NodeCommandBase extends DefaultCommandBase {
+  static flags = {
+    url: flags.string({
+      char: 'u',
+      description: 'Distributor node operator api base url (ie. http://localhost:3335)',
+      required: true,
+    }),
+    secret: flags.string({
+      char: 's',
+      description: 'HMAC secret key to use (will default to config.operatorApi.hmacSecret if present)',
+      required: false,
+    }),
+    ...DefaultCommandBase.flags,
+  }
+
+  protected abstract reqUrl(): string
+
+  protected reqBody(): Record<string, unknown> {
+    return {}
+  }
+
+  async run(): Promise<void> {
+    const { url, secret } = this.parse(this.constructor as typeof NodeCommandBase).flags
+
+    const hmacSecret = secret || this.appConfig.operatorApi?.hmacSecret
+
+    if (!hmacSecret) {
+      this.error('No --secret was provided and no config.operatorApi.hmacSecret is set!', {
+        exit: ExitCodes.InvalidInput,
+      })
+    }
+
+    const reqUrl = this.reqUrl()
+    const reqBody = this.reqBody()
+    const payload = { reqUrl, reqBody }
+    try {
+      await axios.post(urljoin(url, reqUrl), reqBody, {
+        headers: {
+          authorization: `bearer ${jwt.sign(payload, hmacSecret, { expiresIn: 60 })}`,
+        },
+      })
+      this.log('Request successful')
+    } catch (e) {
+      if (axios.isAxiosError(e)) {
+        this.error(`Request failed: ${e.response ? JSON.stringify(e.response.data) : e.message}`, {
+          exit: ExitCodes.ApiError,
+        })
+      }
+      this.error(e instanceof Error ? e.message : JSON.stringify(e), { exit: ExitCodes.ApiError })
+    }
+  }
+}

+ 111 - 0
distributor-node/src/commands/dev/batchUpload.ts

@@ -0,0 +1,111 @@
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase, { flags } from '../../command-base/default'
+import FormData from 'form-data'
+import imgGen from 'js-image-generator'
+import { SubmittableExtrinsic } from '@polkadot/api/types'
+import { BagIdParserService } from '../../services/parsers/BagIdParserService'
+import axios from 'axios'
+import { ContentHash } from '../../services/crypto/ContentHash'
+import urljoin from 'url-join'
+
+async function generateRandomImage(): Promise<Buffer> {
+  return new Promise((resolve, reject) => {
+    imgGen.generateImage(10, 10, 80, function (err: unknown, image: { data: Buffer }) {
+      if (err) {
+        reject(err)
+      } else {
+        resolve(image.data)
+      }
+    })
+  })
+}
+
+export default class DevBatchUpload extends AccountsCommandBase {
+  static flags = {
+    ...DefaultCommandBase.flags,
+    bagId: flags.string({
+      char: 'b',
+      required: true,
+    }),
+    bucketId: flags.integer({
+      char: 'B',
+      description: 'Storage bucket id',
+      required: true,
+    }),
+    batchSize: flags.integer({
+      char: 'S',
+      required: true,
+    }),
+    batchesCount: flags.integer({
+      char: 'C',
+      required: true,
+    }),
+    endpoint: flags.string({
+      char: 'e',
+      required: true,
+    }),
+  }
+
+  async run(): Promise<void> {
+    const { api } = this
+    const { bagId, bucketId, batchSize, batchesCount, endpoint } = this.parse(DevBatchUpload).flags
+    const sudoKey = (await api.query.sudo.key()).toHuman()
+    const dataFee = await api.query.storage.dataObjectPerMegabyteFee()
+
+    for (let i = 0; i < batchesCount; ++i) {
+      const nextObjectId = (await api.query.storage.nextDataObjectId()).toNumber()
+      // Generate batch
+      const batch: [SubmittableExtrinsic<'promise'>, Buffer][] = []
+      for (let j = 0; j < batchSize; ++j) {
+        const dataObject = await generateRandomImage()
+        const dataHash = new ContentHash().update(dataObject).digest()
+        batch.push([
+          api.tx.sudo.sudo(
+            api.tx.storage.sudoUploadDataObjects({
+              deletionPrizeSourceAccountId: sudoKey,
+              objectCreationList: [
+                {
+                  Size: dataObject.byteLength,
+                  IpfsContentId: dataHash,
+                },
+              ],
+              expectedDataSizeFee: dataFee,
+              bagId: new BagIdParserService(bagId).parse(),
+            })
+          ),
+          dataObject,
+        ])
+      }
+      // Send batch
+      await this.sendAndFollowTx(this.getPair(sudoKey), api.tx.utility.batch(batch.map(([tx]) => tx)))
+
+      // Send storage node uploads
+      await Promise.all(
+        batch.map(async ([, dataObject], k) => {
+          const dataObjectId = nextObjectId + k
+          const formData = new FormData()
+          formData.append('dataObjectId', dataObjectId.toString())
+          formData.append('storageBucketId', bucketId.toString())
+          formData.append('bagId', bagId)
+          formData.append('file', dataObject, { filename: 'test.jpg', knownLength: dataObject.byteLength })
+          this.log(`Uploading object ${dataObjectId}`)
+          try {
+            await axios({
+              method: 'POST',
+              url: urljoin(endpoint, 'api/v1/files'),
+              data: formData,
+              headers: {
+                'content-type': 'multipart/form-data',
+                ...formData.getHeaders(),
+              },
+            })
+          } catch (e) {
+            if (axios.isAxiosError(e)) {
+              console.log(e.response?.data)
+            }
+          }
+        })
+      )
+    }
+  }
+}

+ 93 - 0
distributor-node/src/commands/dev/init.ts

@@ -0,0 +1,93 @@
+import { MemberId } from '@joystream/types/members'
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase from '../../command-base/default'
+
+const ALICE = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'
+
+export default class DevInit extends AccountsCommandBase {
+  static description = 'Initialize development environment. Sets Alice as distributor working group leader.'
+
+  static flags = {
+    ...DefaultCommandBase.flags,
+  }
+
+  async run(): Promise<void> {
+    const { api } = this
+
+    if (!api.isDevelopment) {
+      this.error('Not connected to dev chain!')
+    }
+
+    const SudoKeyPair = this.getPair(ALICE)
+    const LeadKeyPair = this.getPair(ALICE)
+
+    // Create membership if not already created
+    const members = await api.query.members.memberIdsByControllerAccountId(LeadKeyPair.address)
+
+    let memberId: MemberId | undefined = members.toArray()[0]
+
+    if (memberId === undefined) {
+      const res = await this.api.sendExtrinsic(LeadKeyPair, api.tx.members.buyMembership(0, 'alice', null, null))
+      memberId = this.api.getEvent(res, 'members', 'MemberRegistered').data[0]
+    }
+
+    // Create a new lead opening.
+    const currentLead = await api.query.distributionWorkingGroup.currentLead()
+    if (currentLead.isSome) {
+      this.log('Distributor lead already exists, skipping...')
+      return
+    }
+
+    this.log(`Making member id: ${memberId} the distribution lead.`)
+
+    // Create curator lead opening
+    const addOpeningRes = await this.api.sendExtrinsic(
+      SudoKeyPair,
+      this.api.sudo(
+        api.tx.distributionWorkingGroup.addOpening(
+          { CurrentBlock: null },
+          { max_review_period_length: 9999 },
+          'dev distributor lead opening',
+          'Leader'
+        )
+      )
+    )
+
+    const openingAddedEvent = this.api.getEvent(addOpeningRes, 'distributionWorkingGroup', 'OpeningAdded')
+    const openingId = openingAddedEvent.data[0]
+
+    // Apply to lead opening
+    const applyRes = await this.api.sendExtrinsic(
+      LeadKeyPair,
+      this.api.tx.distributionWorkingGroup.applyOnOpening(
+        memberId, // member id
+        openingId, // opening id
+        LeadKeyPair.address, // address
+        null, // opt role stake
+        null, // opt appl. stake
+        'dev distributor lead application' // human_readable_text
+      )
+    )
+
+    const appliedEvent = this.api.getEvent(applyRes, 'distributionWorkingGroup', 'AppliedOnOpening')
+    const applicationId = appliedEvent.data[1]
+
+    // Begin review period
+    await this.api.sendExtrinsic(
+      SudoKeyPair,
+      this.api.sudo(this.api.tx.distributionWorkingGroup.beginApplicantReview(openingId))
+    )
+
+    // Fill opening
+    await this.api.sendExtrinsic(
+      SudoKeyPair,
+      this.api.sudo(
+        this.api.tx.distributionWorkingGroup.fillOpening(
+          openingId,
+          api.createType('ApplicationIdSet', [applicationId]),
+          null
+        )
+      )
+    )
+  }
+}

+ 34 - 0
distributor-node/src/commands/leader/cancel-invitation.ts

@@ -0,0 +1,34 @@
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase, { flags } from '../../command-base/default'
+
+export default class LeaderCancelInvitation extends AccountsCommandBase {
+  static description = `Cancel pending distribution bucket operator invitation.
+  Requires distribution working group leader permissions.`
+
+  static flags = {
+    bucketId: flags.bucketId({
+      required: true,
+    }),
+    workerId: flags.integer({
+      char: 'w',
+      description: 'ID of the invited operator (distribution group worker)',
+      required: true,
+    }),
+    ...DefaultCommandBase.flags,
+  }
+
+  async run(): Promise<void> {
+    const { bucketId, workerId } = this.parse(LeaderCancelInvitation).flags
+    const leadKey = await this.getDistributorLeadKey()
+
+    this.log(`Canceling distribution bucket operator invitation...`, {
+      bucketId: bucketId.toHuman(),
+      workerId: workerId,
+    })
+    await this.sendAndFollowTx(
+      await this.getDecodedPair(leadKey),
+      this.api.tx.storage.cancelDistributionBucketOperatorInvite(bucketId, workerId)
+    )
+    this.log('Invitation succesfully canceled!')
+  }
+}

+ 25 - 0
distributor-node/src/commands/leader/create-bucket-family.ts

@@ -0,0 +1,25 @@
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase from '../../command-base/default'
+
+export default class LeaderCreateBucketFamily extends AccountsCommandBase {
+  static description = `Create new distribution bucket family. Requires distribution working group leader permissions.`
+
+  static flags = {
+    ...DefaultCommandBase.flags,
+  }
+
+  async run(): Promise<void> {
+    const leadKey = await this.getDistributorLeadKey()
+
+    this.log('Creating new distribution bucket family...')
+    const result = await this.sendAndFollowTx(
+      await this.getDecodedPair(leadKey),
+      this.api.tx.storage.createDistributionBucketFamily()
+    )
+    const event = this.api.getEvent(result, 'storage', 'DistributionBucketFamilyCreated')
+
+    this.log('Bucket family succesfully created!')
+    const bucketFamilyId = event.data[0]
+    this.output(bucketFamilyId.toString())
+  }
+}

+ 41 - 0
distributor-node/src/commands/leader/create-bucket.ts

@@ -0,0 +1,41 @@
+import { flags } from '@oclif/command'
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase from '../../command-base/default'
+
+export default class LeaderCreateBucket extends AccountsCommandBase {
+  static description = `Create new distribution bucket. Requires distribution working group leader permissions.`
+
+  static flags = {
+    familyId: flags.integer({
+      char: 'f',
+      description: 'Distribution bucket family id',
+      required: true,
+    }),
+    acceptingBags: flags.enum({
+      char: 'a',
+      description: 'Whether the created bucket should accept new bags',
+      options: ['yes', 'no'],
+      default: 'no',
+    }),
+    ...DefaultCommandBase.flags,
+  }
+
+  async run(): Promise<void> {
+    const { familyId, acceptingBags } = this.parse(LeaderCreateBucket).flags
+    const leadKey = await this.getDistributorLeadKey()
+
+    this.log('Creating new distribution bucket...', {
+      familyId,
+      acceptingBags,
+    })
+    const result = await this.sendAndFollowTx(
+      await this.getDecodedPair(leadKey),
+      this.api.tx.storage.createDistributionBucket(familyId, acceptingBags === 'yes')
+    )
+    const event = this.api.getEvent(result, 'storage', 'DistributionBucketCreated')
+
+    this.log('Bucket succesfully created!')
+    const bucketId = event.data[2]
+    this.output(bucketId.distribution_bucket_index.toString())
+  }
+}

+ 28 - 0
distributor-node/src/commands/leader/delete-bucket-family.ts

@@ -0,0 +1,28 @@
+import { flags } from '@oclif/command'
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase from '../../command-base/default'
+
+export default class LeaderDeleteBucketFamily extends AccountsCommandBase {
+  static description = `Delete distribution bucket family. Requires distribution working group leader permissions.`
+
+  static flags = {
+    familyId: flags.integer({
+      char: 'f',
+      description: 'Distribution bucket family id',
+      required: true,
+    }),
+    ...DefaultCommandBase.flags,
+  }
+
+  async run(): Promise<void> {
+    const { familyId } = this.parse(LeaderDeleteBucketFamily).flags
+    const leadKey = await this.getDistributorLeadKey()
+
+    this.log(`Deleting distribution bucket family...`, { familyId })
+    await this.sendAndFollowTx(
+      await this.getDecodedPair(leadKey),
+      this.api.tx.storage.deleteDistributionBucketFamily(familyId)
+    )
+    this.log('Bucket family succesfully deleted!')
+  }
+}

+ 25 - 0
distributor-node/src/commands/leader/delete-bucket.ts

@@ -0,0 +1,25 @@
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase, { flags } from '../../command-base/default'
+
+export default class LeaderDeleteBucket extends AccountsCommandBase {
+  static description = `Delete distribution bucket. The bucket must have no operators. Requires distribution working group leader permissions.`
+
+  static flags = {
+    bucketId: flags.bucketId({
+      required: true,
+    }),
+    ...DefaultCommandBase.flags,
+  }
+
+  async run(): Promise<void> {
+    const { bucketId } = this.parse(LeaderDeleteBucket).flags
+    const leadKey = await this.getDistributorLeadKey()
+
+    this.log(`Deleting distribution bucket...`, { bucketId: bucketId.toHuman() })
+    await this.sendAndFollowTx(
+      await this.getDecodedPair(leadKey),
+      this.api.tx.storage.deleteDistributionBucket(bucketId)
+    )
+    this.log('Bucket succesfully deleted!')
+  }
+}

+ 35 - 0
distributor-node/src/commands/leader/invite-bucket-operator.ts

@@ -0,0 +1,35 @@
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase, { flags } from '../../command-base/default'
+
+export default class LeaderInviteBucketOperator extends AccountsCommandBase {
+  static description = `Invite distribution bucket operator (distribution group worker).
+  The specified bucket must not have any operator currently.
+  Requires distribution working group leader permissions.`
+
+  static flags = {
+    bucketId: flags.bucketId({
+      required: true,
+    }),
+    workerId: flags.integer({
+      char: 'w',
+      description: 'ID of the distribution group worker to invite as bucket operator',
+      required: true,
+    }),
+    ...DefaultCommandBase.flags,
+  }
+
+  async run(): Promise<void> {
+    const { bucketId, workerId } = this.parse(LeaderInviteBucketOperator).flags
+    const leadKey = await this.getDistributorLeadKey()
+
+    this.log(`Inviting distribution bucket operator...`, {
+      bucketId: bucketId.toHuman(),
+      workerId,
+    })
+    await this.sendAndFollowTx(
+      await this.getDecodedPair(leadKey),
+      this.api.tx.storage.inviteDistributionBucketOperator(bucketId, workerId)
+    )
+    this.log('Bucket operator succesfully invited!')
+  }
+}

+ 34 - 0
distributor-node/src/commands/leader/remove-bucket-operator.ts

@@ -0,0 +1,34 @@
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase, { flags } from '../../command-base/default'
+
+export default class LeaderRemoveBucketOperator extends AccountsCommandBase {
+  static description = `Remove distribution bucket operator (distribution group worker).
+  Requires distribution working group leader permissions.`
+
+  static flags = {
+    bucketId: flags.bucketId({
+      required: true,
+    }),
+    workerId: flags.integer({
+      char: 'w',
+      description: 'ID of the operator (distribution working group worker) to remove from the bucket',
+      required: true,
+    }),
+    ...DefaultCommandBase.flags,
+  }
+
+  async run(): Promise<void> {
+    const { bucketId, workerId } = this.parse(LeaderRemoveBucketOperator).flags
+    const leadKey = await this.getDistributorLeadKey()
+
+    this.log(`Removing distribution bucket operator...`, {
+      bucketId: bucketId.toHuman(),
+      workerId,
+    })
+    await this.sendAndFollowTx(
+      await this.getDecodedPair(leadKey),
+      this.api.tx.storage.removeDistributionBucketOperator(bucketId, workerId)
+    )
+    this.log('Bucket operator succesfully removed!')
+  }
+}

+ 89 - 0
distributor-node/src/commands/leader/set-bucket-family-metadata.ts

@@ -0,0 +1,89 @@
+import fs from 'fs'
+import AccountsCommandBase from '../../command-base/accounts'
+import DefaultCommandBase, { flags } from '../../command-base/default'
+import { ValidationService } from '../../services/validation/ValidationService'
+import {
+  DistributionBucketFamilyMetadata,
+  GeographicalArea,
+  IDistributionBucketFamilyMetadata,
+} from '@joystream/metadata-protobuf'
+import { FamilyMetadataJson } from '../../types/generated/FamilyMetadataJson'
+import { isValidCountryCode, isValidSubdivisionCode } from '@joystream/metadata-protobuf/utils'
+import ExitCodes from '../../command-base/ExitCodes'
+
+export default class LeaderSetBucketFamilyMetadata extends AccountsCommandBase {
+  static description = `Set/update distribution bucket family metadata.
+  Requires distribution working group leader permissions.`
+
+  static flags = {
+    familyId: flags.integer({
+      char: 'f',
+      description: 'Distribution bucket family id',
+      required: true,
+    }),
+    input: flags.string({
+      char: 'i',
+      description: 'Path to JSON metadata file',
+      required: true,
+    }),
+    ...DefaultCommandBase.flags,
+  }
+
+  parseAndValidateMetadata(input: FamilyMetadataJson): IDistributionBucketFamilyMetadata {
+    const areas: IDistributionBucketFamilyMetadata['areas'] = []
+    input.areas?.forEach((a) => {
+      if ('continentCode' in a && a.continentCode) {
+        areas.push({ continent: GeographicalArea.Continent[a.continentCode] })
+        return
+      }
+      if ('countryCode' in a && a.countryCode) {
+        if (!isValidCountryCode(a.countryCode)) {
+          this.error(`Invalid country code: ${a.countryCode}`, { exit: ExitCodes.InvalidInput })
+        }
+        areas.push({ countryCode: a.countryCode })
+        return
+      }
+      if ('subdivisionCode' in a && a.subdivisionCode) {
+        if (!isValidSubdivisionCode(a.subdivisionCode)) {
+          this.error(`Invalid subdivision code: ${a.subdivisionCode}`, { exit: ExitCodes.InvalidInput })
+        }
+        areas.push({ subdivisionCode: a.subdivisionCode })
+        return
+      }
+      areas.push({})
+    })
+
+    const meta = { ...input, areas }
+    const error = DistributionBucketFamilyMetadata.verify(meta)
+    if (error) {
+      this.error(`Metadata validation failed: ${error}`, { exit: ExitCodes.InvalidInput })
+    }
+
+    return meta
+  }
+
+  async run(): Promise<void> {
+    const { familyId, input } = this.parse(LeaderSetBucketFamilyMetadata).flags
+    const leadKey = await this.getDistributorLeadKey()
+
+    const validation = new ValidationService()
+    const metadataInput: FamilyMetadataJson = validation.validate(
+      'FamilyMetadata',
+      JSON.parse(fs.readFileSync(input).toString())
+    )
+    const metadata = this.parseAndValidateMetadata(metadataInput)
+
+    this.log(`Setting bucket family metadata`, {
+      familyId,
+      metadata,
+    })
+    await this.sendAndFollowTx(
+      await this.getDecodedPair(leadKey),
+      this.api.tx.storage.setDistributionBucketFamilyMetadata(
+        familyId,
+        '0x' + Buffer.from(DistributionBucketFamilyMetadata.encode(metadata).finish()).toString('hex')
+      )
+    )
+    this.log('Bucket family metadata succesfully set/updated!')
+  }
+}

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