file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
XML.py
#!/usr/bin/env python3 # XML API, for dealing with XML strings # -*- coding: utf-8 -*- __all__ = ['parseargs', 'collect'] '<users>\n\t<user>\n\t\t<id>1</id>\n\t\t<name>Fred</name>\n\t\t<salary>500000</salary>\n\t</user>\n\t<user>\n\t\t<id>1</id>\n\t\t<name>ScienceCat</name>\n\t\t<salary>500000</salary>\n\t</user>\n\t<user>\n\t\t<id>1</id>\n\t\t<name>Bob</name>\n\t\t<salary>500000</salary>\n\t</user>\n</users>' xmlex = '<users>\n<user>\n<id>1</id>\n<name>Fred</name>\n<salary>500000</salary>\n</user>\n<user>\n<id>1</id>\n<name>ScienceCat</name>\n<salary>500000</salary>\n</user>\n<user>\n<id>1</id>\n<name>Bob</name>\n<salary>500000</salary>\n</user>\n</users>' argex = 'cats="True and Sand" true=\'Cats two\' sand="graval"' ##import re ##import xml.etree.cElementTree as xml def parseargs(string:str): """Split a given string into individual arguments, seperated into key:arg for <key>=(' or ")<arg>(same char as start)""" arg = {} # ([%-%w]+)=([\"'])(.-)%2 # '([\w]+)=([\"\'])(.*)' # '([-\w]+)=([\"\']*)' ## pattern = re.compile('([\w]+)=([\"\'])(.*)') ## print(pattern) ## for match in re.findall(pattern, string): ## print(match) parts = string.split(' ') bkey = '' buffer = '' end = '"' for part in parts: if '=' in part: key, vp = part.split('=') if vp[0] in ('"', "'"): end = vp[0] if vp.endswith(end): arg[key] = vp[1:-1] else: bkey = key buffer += vp elif part.endswith(end): buffer += ' '+part arg[bkey] = buffer[1:-1] bkey, buffer = '', '' else: buffer += ' '+part return arg def collect(string:str): stack = [] top = [] stack.append(top) i, j = 0, 0 class elementTag:
while True: ni h c lable xarg emtpy if not ni: break text = string[i:ni-1] if not text.find('^ '): top.append(text) if empty == '/':# empty element tag top.append(elementTag(label, parseargs(xarg), 1)) elif c == '': # start tag top = [elementTag(label, parseargs(xarg))] stack.append(top) else: toclose = stack if len(stack) < 1: error(f'Nothing to close with {label}.') elif toclose.label == label: pass
def __init__(self, label, xargs, empty=0): self.label = label self.xargs = xargs self.empty = empty
utils.py
import numpy as np import matplotlib.pyplot as plt def train_test_splitter(X, y, ratio = 0.8, random_seed = 0): assert(len(X) == len(y)), "The number of points in feature matrix and target vector should be the same." np.random.seed(random_seed) n = len(y) idx = np.arange(n) np.random.shuffle(idx) train_idx = idx[:int(n * ratio)] test_idx = idx[int(n * ratio):] return X[train_idx,:], X[test_idx,:], y[train_idx], y[test_idx] def error_rate(y, y_predicted): assert len(y) == len(y_predicted), "The number of targets and predictions should be the same." assert len(y) != 0, "The number of targets and predictions should not be zero." return np.sum(np.array(y) != np.array(y_predicted)) / len(y)
fig = plt.figure(figsize = (12,8)) plt.plot(np.arange(len(losses)), losses, color = 'r', marker = 'o', label = 'Loss') plt.legend() plt.ylabel('Loss') plt.xlabel('Number of Iterations') if savefig: fig.savefig(filename, format = 'png', dpi = 600, bbox_inches = 'tight') if showfig: plt.show() plt.close() return
def plot_losses(losses, savefig = False, showfig = False, filename = 'loss.png'):
ipam_vlan_groups_bulk_update_parameters.go
// Code generated by go-swagger; DO NOT EDIT. // Copyright 2020 The go-netbox Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package ipam // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "net/http" "time" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/tomasherout/go-netbox/netbox/models" ) // NewIpamVlanGroupsBulkUpdateParams creates a new IpamVlanGroupsBulkUpdateParams object, // with the default timeout for this client. // // Default values are not hydrated, since defaults are normally applied by the API server side. // // To enforce default values in parameter, use SetDefaults or WithDefaults. func NewIpamVlanGroupsBulkUpdateParams() *IpamVlanGroupsBulkUpdateParams { return &IpamVlanGroupsBulkUpdateParams{ timeout: cr.DefaultTimeout, } } // NewIpamVlanGroupsBulkUpdateParamsWithTimeout creates a new IpamVlanGroupsBulkUpdateParams object // with the ability to set a timeout on a request. func NewIpamVlanGroupsBulkUpdateParamsWithTimeout(timeout time.Duration) *IpamVlanGroupsBulkUpdateParams { return &IpamVlanGroupsBulkUpdateParams{ timeout: timeout, } } // NewIpamVlanGroupsBulkUpdateParamsWithContext creates a new IpamVlanGroupsBulkUpdateParams object // with the ability to set a context for a request. func NewIpamVlanGroupsBulkUpdateParamsWithContext(ctx context.Context) *IpamVlanGroupsBulkUpdateParams { return &IpamVlanGroupsBulkUpdateParams{ Context: ctx, } } // NewIpamVlanGroupsBulkUpdateParamsWithHTTPClient creates a new IpamVlanGroupsBulkUpdateParams object // with the ability to set a custom HTTPClient for a request. func NewIpamVlanGroupsBulkUpdateParamsWithHTTPClient(client *http.Client) *IpamVlanGroupsBulkUpdateParams { return &IpamVlanGroupsBulkUpdateParams{ HTTPClient: client, } } /* IpamVlanGroupsBulkUpdateParams contains all the parameters to send to the API endpoint for the ipam vlan groups bulk update operation. Typically these are written to a http.Request. */ type IpamVlanGroupsBulkUpdateParams struct { // Data. Data *models.VLANGroup timeout time.Duration Context context.Context HTTPClient *http.Client } // WithDefaults hydrates default values in the ipam vlan groups bulk update params (not the query body). // // All values with no default are reset to their zero value. func (o *IpamVlanGroupsBulkUpdateParams) WithDefaults() *IpamVlanGroupsBulkUpdateParams { o.SetDefaults() return o } // SetDefaults hydrates default values in the ipam vlan groups bulk update params (not the query body). // // All values with no default are reset to their zero value. func (o *IpamVlanGroupsBulkUpdateParams) SetDefaults() { // no default values defined for this parameter } // WithTimeout adds the timeout to the ipam vlan groups bulk update params func (o *IpamVlanGroupsBulkUpdateParams) WithTimeout(timeout time.Duration) *IpamVlanGroupsBulkUpdateParams { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the ipam vlan groups bulk update params func (o *IpamVlanGroupsBulkUpdateParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the ipam vlan groups bulk update params func (o *IpamVlanGroupsBulkUpdateParams) WithContext(ctx context.Context) *IpamVlanGroupsBulkUpdateParams { o.SetContext(ctx) return o } // SetContext adds the context to the ipam vlan groups bulk update params func (o *IpamVlanGroupsBulkUpdateParams) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the ipam vlan groups bulk update params func (o *IpamVlanGroupsBulkUpdateParams) WithHTTPClient(client *http.Client) *IpamVlanGroupsBulkUpdateParams { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the ipam vlan groups bulk update params func (o *IpamVlanGroupsBulkUpdateParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithData adds the data to the ipam vlan groups bulk update params func (o *IpamVlanGroupsBulkUpdateParams) WithData(data *models.VLANGroup) *IpamVlanGroupsBulkUpdateParams { o.SetData(data) return o } // SetData adds the data to the ipam vlan groups bulk update params func (o *IpamVlanGroupsBulkUpdateParams) SetData(data *models.VLANGroup) { o.Data = data } // WriteToRequest writes these params to a swagger request func (o *IpamVlanGroupsBulkUpdateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.Data != nil { if err := r.SetBodyParam(o.Data); err != nil { return err } } if len(res) > 0 { return errors.CompositeValidationError(res...)
} return nil }
delta_arrow.rs
//! Conversion between Delta Table schema and Arrow schema use crate::schema; use arrow::datatypes::{ DataType as ArrowDataType, Field as ArrowField, Schema as ArrowSchema, SchemaRef, TimeUnit, }; use arrow::error::ArrowError; use lazy_static::lazy_static; use regex::Regex; use std::convert::TryFrom; impl TryFrom<&schema::Schema> for ArrowSchema { type Error = ArrowError; fn try_from(s: &schema::Schema) -> Result<Self, ArrowError> { let fields = s .get_fields() .iter() .map(|field| <ArrowField as TryFrom<&schema::SchemaField>>::try_from(field)) .collect::<Result<Vec<ArrowField>, ArrowError>>()?; Ok(ArrowSchema::new(fields)) } } impl TryFrom<&schema::SchemaField> for ArrowField { type Error = ArrowError; fn try_from(f: &schema::SchemaField) -> Result<Self, ArrowError> { Ok(ArrowField::new( f.get_name(), ArrowDataType::try_from(f.get_type())?, f.is_nullable(), )) } } impl TryFrom<&schema::SchemaTypeArray> for ArrowField { type Error = ArrowError; fn try_from(a: &schema::SchemaTypeArray) -> Result<Self, ArrowError> { Ok(ArrowField::new( "element", ArrowDataType::try_from(a.get_element_type())?, a.contains_null(), )) } } impl TryFrom<&schema::SchemaDataType> for ArrowDataType { type Error = ArrowError; fn try_from(t: &schema::SchemaDataType) -> Result<Self, ArrowError>
} pub(crate) fn delta_log_schema_for_table( table_schema: ArrowSchema, partition_columns: &[String], ) -> SchemaRef { lazy_static! { static ref SCHEMA_FIELDS: Vec<ArrowField> = vec![ ArrowField::new( "metaData", ArrowDataType::Struct(vec![ ArrowField::new("id", ArrowDataType::Utf8, true), ArrowField::new("name", ArrowDataType::Utf8, true), ArrowField::new("description", ArrowDataType::Utf8, true), ArrowField::new("schemaString", ArrowDataType::Utf8, true), ArrowField::new("createdTime", ArrowDataType::Int64, true), ArrowField::new("partitionColumns", ArrowDataType::List(Box::new( ArrowField::new("element", ArrowDataType::Utf8, true))), true), ArrowField::new("format", ArrowDataType::Struct(vec![ ArrowField::new("provider", ArrowDataType::Utf8, true), // TODO: Add "options" after ArrowDataType::Map support ]), true), ]), true ), ArrowField::new( "protocol", ArrowDataType::Struct(vec![ ArrowField::new("minReaderVersion", ArrowDataType::Int32, true), ArrowField::new("minWriterVersion", ArrowDataType::Int32, true), ]), true ), ArrowField::new( "txn", ArrowDataType::Struct(vec![ ArrowField::new("appId", ArrowDataType::Utf8, true), ArrowField::new("version", ArrowDataType::Int64, true), ]), true ), ArrowField::new( "remove", ArrowDataType::Struct(vec![ ArrowField::new("path", ArrowDataType::Utf8, true), ArrowField::new("deletionTimestamp", ArrowDataType::Int64, true), ArrowField::new("dataChange", ArrowDataType::Boolean, true), ArrowField::new("extendedFileMetadata", ArrowDataType::Boolean, true), ArrowField::new("size", ArrowDataType::Int64, true), // TODO: Add "partitionValues" after ArrowDataType::Map support // TODO: Add "tags" after ArrowDataType::Map support ]), true ) ]; static ref ADD_FIELDS: Vec<ArrowField> = vec![ ArrowField::new("path", ArrowDataType::Utf8, true), ArrowField::new("size", ArrowDataType::Int64, true), ArrowField::new("modificationTime", ArrowDataType::Int64, true), ArrowField::new("dataChange", ArrowDataType::Boolean, true), ArrowField::new("stats", ArrowDataType::Utf8, true), // TODO: Add "partitionValues" after ArrowDataType::Map support // TODO: Add "tags" after ArrowDataType::Map support ]; } let (partition_fields, non_partition_fields): (Vec<ArrowField>, Vec<ArrowField>) = table_schema .fields() .iter() .map(|f| f.to_owned()) .partition(|field| partition_columns.contains(&field.name())); let mut stats_parsed_fields: Vec<ArrowField> = vec![ArrowField::new("numRecords", ArrowDataType::Int64, true)]; if !non_partition_fields.is_empty() { stats_parsed_fields.extend(["minValues", "maxValues", "nullCounts"].iter().map(|name| { ArrowField::new( name, ArrowDataType::Struct(non_partition_fields.clone()), true, ) })); } let mut add_fields = ADD_FIELDS.clone(); add_fields.push(ArrowField::new( "stats_parsed", ArrowDataType::Struct(stats_parsed_fields), true, )); if !partition_fields.is_empty() { add_fields.push(ArrowField::new( "partitionValues_parsed", ArrowDataType::Struct(partition_fields), true, )); } let mut schema_fields = SCHEMA_FIELDS.clone(); schema_fields.push(ArrowField::new( "add", ArrowDataType::Struct(add_fields), true, )); let arrow_schema = ArrowSchema::new(schema_fields); std::sync::Arc::new(arrow_schema) } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; #[test] fn delta_log_schema_for_table_test() { // NOTE: We should future proof the checkpoint schema in case action schema changes. // See https://github.com/delta-io/delta-rs/issues/287 let table_schema = ArrowSchema::new(vec![ ArrowField::new("pcol", ArrowDataType::Int32, true), ArrowField::new("col1", ArrowDataType::Int32, true), ]); let partition_columns = vec!["pcol".to_string()]; let log_schema = delta_log_schema_for_table(table_schema, partition_columns.as_slice()); let expected_fields = vec!["metaData", "protocol", "txn", "remove", "add"]; for f in log_schema.fields().iter() { assert!(expected_fields.contains(&f.name().as_str())); } let add_fields: Vec<_> = log_schema .fields() .iter() .filter(|f| f.name() == "add") .map(|f| { if let ArrowDataType::Struct(fields) = f.data_type() { fields.iter().map(|f| f.clone()) } else { unreachable!(); } }) .flatten() .collect(); assert_eq!(7, add_fields.len()); let add_field_map: HashMap<_, _> = add_fields .iter() .map(|f| (f.name().to_owned(), f.clone())) .collect(); let partition_values_parsed = add_field_map.get("partitionValues_parsed").unwrap(); if let ArrowDataType::Struct(fields) = partition_values_parsed.data_type() { assert_eq!(1, fields.len()); let field = fields.get(0).unwrap().to_owned(); assert_eq!(ArrowField::new("pcol", ArrowDataType::Int32, true), field); } else { unreachable!(); } let stats_parsed = add_field_map.get("stats_parsed").unwrap(); if let ArrowDataType::Struct(fields) = stats_parsed.data_type() { assert_eq!(4, fields.len()); let field_map: HashMap<_, _> = fields .iter() .map(|f| (f.name().to_owned(), f.clone())) .collect(); for (k, v) in field_map.iter() { match k.as_ref() { "minValues" | "maxValues" | "nullCounts" => match v.data_type() { ArrowDataType::Struct(fields) => { assert_eq!(1, fields.len()); let field = fields.get(0).unwrap().to_owned(); assert_eq!(ArrowField::new("col1", ArrowDataType::Int32, true), field); } _ => unreachable!(), }, "numRecords" => {} _ => panic!(), } } } else { unreachable!(); } } }
{ match t { schema::SchemaDataType::primitive(p) => { lazy_static! { static ref DECIMAL_REGEX: Regex = Regex::new(r"\((\d{1,2}),(\d{1,2})\)").unwrap(); } match p.as_str() { "string" => Ok(ArrowDataType::Utf8), "long" => Ok(ArrowDataType::Int64), // undocumented type "integer" => Ok(ArrowDataType::Int32), "short" => Ok(ArrowDataType::Int16), "byte" => Ok(ArrowDataType::Int8), "float" => Ok(ArrowDataType::Float32), "double" => Ok(ArrowDataType::Float64), "boolean" => Ok(ArrowDataType::Boolean), "binary" => Ok(ArrowDataType::Binary), decimal if DECIMAL_REGEX.is_match(decimal) => { let extract = DECIMAL_REGEX.captures(decimal).ok_or_else(|| { ArrowError::SchemaError(format!( "Invalid decimal type for Arrow: {}", decimal.to_string() )) })?; let precision = extract .get(1) .and_then(|v| v.as_str().parse::<usize>().ok()); let scale = extract .get(2) .and_then(|v| v.as_str().parse::<usize>().ok()); match (precision, scale) { (Some(p), Some(s)) => Ok(ArrowDataType::Decimal(p, s)), _ => Err(ArrowError::SchemaError(format!( "Invalid precision or scale decimal type for Arrow: {}", decimal.to_string() ))), } } "date" => { // A calendar date, represented as a year-month-day triple without a // timezone. Ok(ArrowDataType::Date32) } "timestamp" => { // Issue: https://github.com/delta-io/delta/issues/643 Ok(ArrowDataType::Timestamp(TimeUnit::Nanosecond, None)) } s => Err(ArrowError::SchemaError(format!( "Invalid data type for Arrow: {}", s.to_string() ))), } } schema::SchemaDataType::r#struct(s) => Ok(ArrowDataType::Struct( s.get_fields() .iter() .map(|f| <ArrowField as TryFrom<&schema::SchemaField>>::try_from(f)) .collect::<Result<Vec<ArrowField>, ArrowError>>()?, )), schema::SchemaDataType::array(a) => { Ok(ArrowDataType::List(Box::new(<ArrowField as TryFrom< &schema::SchemaTypeArray, >>::try_from( a )?))) } // NOTE: this doesn't currently support maps with string keys // See below arrow-rs issues for adding arrow::datatypes::DataType::Map to support a // more general map type: // https://github.com/apache/arrow-rs/issues/395 // https://github.com/apache/arrow-rs/issues/396 schema::SchemaDataType::map(m) => Ok(ArrowDataType::Dictionary( Box::new( <ArrowDataType as TryFrom<&schema::SchemaDataType>>::try_from( m.get_key_type(), )?, ), Box::new( <ArrowDataType as TryFrom<&schema::SchemaDataType>>::try_from( m.get_value_type(), )?, ), )), } }
middleware.go
package middleware import ( "context" "github.com/haogooder/gospanner/mongo/field" "github.com/haogooder/gospanner/mongo/hook" "github.com/haogooder/gospanner/mongo/operator" "github.com/haogooder/gospanner/mongo/validator" ) // callback define the callback function type type callback func(ctx context.Context, doc interface{}, opType operator.OpType, opts ...interface{}) error // middlewareCallback the register callback slice // some callbacks initial here without Register() for order var middlewareCallback = []callback{ hook.Do, field.Do, validator.Do, } // Register register callback into middleware func Register(cb callback) { middlewareCallback = append(middlewareCallback, cb) } // Do call every registers // The doc is always the document to operate func Do(ctx context.Context, doc interface{}, opType operator.OpType, opts ...interface{}) error { for _, cb := range middlewareCallback { if err := cb(ctx, doc, opType, opts...); err != nil
} return nil }
{ return err }
gosper.py
"""Gosper's algorithm for hypergeometric summation. """ from sympy.core import S, Dummy, symbols from sympy.core.compatibility import is_sequence from sympy.polys import Poly, parallel_poly_from_expr, factor from sympy.solvers import solve from sympy.simplify import hypersimp def gosper_normal(f, g, n, polys=True): r""" Compute the Gosper's normal form of ``f`` and ``g``. Explanation =========== Given relatively prime univariate polynomials ``f`` and ``g``, rewrite their quotient to a normal form defined as follows: .. math:: \frac{f(n)}{g(n)} = Z \cdot \frac{A(n) C(n+1)}{B(n) C(n)} where ``Z`` is an arbitrary constant and ``A``, ``B``, ``C`` are monic polynomials in ``n`` with the following properties: 1. `\gcd(A(n), B(n+h)) = 1 \forall h \in \mathbb{N}` 2. `\gcd(B(n), C(n+1)) = 1` 3. `\gcd(A(n), C(n)) = 1` This normal form, or rational factorization in other words, is a crucial step in Gosper's algorithm and in solving of difference equations. It can be also used to decide if two hypergeometric terms are similar or not. This procedure will return a tuple containing elements of this factorization in the form ``(Z*A, B, C)``. Examples ======== >>> from sympy.concrete.gosper import gosper_normal >>> from sympy.abc import n >>> gosper_normal(4*n+5, 2*(4*n+1)*(2*n+3), n, polys=False) (1/4, n + 3/2, n + 1/4) """ (p, q), opt = parallel_poly_from_expr( (f, g), n, field=True, extension=True) a, A = p.LC(), p.monic() b, B = q.LC(), q.monic() C, Z = A.one, a/b h = Dummy('h') D = Poly(n + h, n, h, domain=opt.domain) R = A.resultant(B.compose(D)) roots = set(R.ground_roots().keys()) for r in set(roots): if not r.is_Integer or r < 0: roots.remove(r) for i in sorted(roots): d = A.gcd(B.shift(+i)) A = A.quo(d) B = B.quo(d.shift(-i)) for j in range(1, i + 1): C *= d.shift(-j) A = A.mul_ground(Z) if not polys: A = A.as_expr() B = B.as_expr() C = C.as_expr() return A, B, C def gosper_term(f, n):
def gosper_sum(f, k): r""" Gosper's hypergeometric summation algorithm. Explanation =========== Given a hypergeometric term ``f`` such that: .. math :: s_n = \sum_{k=0}^{n-1} f_k and `f(n)` doesn't depend on `n`, returns `g_{n} - g(0)` where `g_{n+1} - g_n = f_n`, or ``None`` if `s_n` cannot be expressed in closed form as a sum of hypergeometric terms. Examples ======== >>> from sympy.concrete.gosper import gosper_sum >>> from sympy.functions import factorial >>> from sympy.abc import n, k >>> f = (4*k + 1)*factorial(k)/factorial(2*k + 1) >>> gosper_sum(f, (k, 0, n)) (-factorial(n) + 2*factorial(2*n + 1))/factorial(2*n + 1) >>> _.subs(n, 2) == sum(f.subs(k, i) for i in [0, 1, 2]) True >>> gosper_sum(f, (k, 3, n)) (-60*factorial(n) + factorial(2*n + 1))/(60*factorial(2*n + 1)) >>> _.subs(n, 5) == sum(f.subs(k, i) for i in [3, 4, 5]) True References ========== .. [1] Marko Petkovsek, Herbert S. Wilf, Doron Zeilberger, A = B, AK Peters, Ltd., Wellesley, MA, USA, 1997, pp. 73--100 """ indefinite = False if is_sequence(k): k, a, b = k else: indefinite = True g = gosper_term(f, k) if g is None: return None if indefinite: result = f*g else: result = (f*(g + 1)).subs(k, b) - (f*g).subs(k, a) if result is S.NaN: try: result = (f*(g + 1)).limit(k, b) - (f*g).limit(k, a) except NotImplementedError: result = None return factor(result)
r""" Compute Gosper's hypergeometric term for ``f``. Explanation =========== Suppose ``f`` is a hypergeometric term such that: .. math:: s_n = \sum_{k=0}^{n-1} f_k and `f_k` doesn't depend on `n`. Returns a hypergeometric term `g_n` such that `g_{n+1} - g_n = f_n`. Examples ======== >>> from sympy.concrete.gosper import gosper_term >>> from sympy.functions import factorial >>> from sympy.abc import n >>> gosper_term((4*n + 1)*factorial(n)/factorial(2*n + 1), n) (-n - 1/2)/(n + 1/4) """ r = hypersimp(f, n) if r is None: return None # 'f' is *not* a hypergeometric term p, q = r.as_numer_denom() A, B, C = gosper_normal(p, q, n) B = B.shift(-1) N = S(A.degree()) M = S(B.degree()) K = S(C.degree()) if (N != M) or (A.LC() != B.LC()): D = {K - max(N, M)} elif not N: D = {K - N + 1, S.Zero} else: D = {K - N + 1, (B.nth(N - 1) - A.nth(N - 1))/A.LC()} for d in set(D): if not d.is_Integer or d < 0: D.remove(d) if not D: return None # 'f(n)' is *not* Gosper-summable d = max(D) coeffs = symbols('c:%s' % (d + 1), cls=Dummy) domain = A.get_domain().inject(*coeffs) x = Poly(coeffs, n, domain=domain) H = A*x.shift(1) - B*x - C solution = solve(H.coeffs(), coeffs) if solution is None: return None # 'f(n)' is *not* Gosper-summable x = x.as_expr().subs(solution) for coeff in coeffs: if coeff not in solution: x = x.subs(coeff, 0) if x.is_zero: return None # 'f(n)' is *not* Gosper-summable else: return B.as_expr()*x/C.as_expr()
rename.rs
use crate::{Range, TextDocumentPositionParams, WorkDoneProgressOptions, WorkDoneProgressParams}; use serde::{Deserialize, Serialize}; #[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct
{ /// Text Document and Position fields #[serde(flatten)] pub text_document_position: TextDocumentPositionParams, /// The new name of the symbol. If the given name is not valid the /// request must return a [ResponseError](#ResponseError) with an /// appropriate message set. pub new_name: String, #[serde(flatten)] pub work_done_progress_params: WorkDoneProgressParams, } #[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RenameOptions { /// Renames should be checked and tested before being executed. #[serde(skip_serializing_if = "Option::is_none")] pub prepare_provider: Option<bool>, #[serde(flatten)] pub work_done_progress_options: WorkDoneProgressOptions, } #[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct RenameClientCapabilities { /// Whether rename supports dynamic registration. #[serde(skip_serializing_if = "Option::is_none")] pub dynamic_registration: Option<bool>, /// Client supports testing for validity of rename operations before execution. /// /// since 3.12.0 #[serde(skip_serializing_if = "Option::is_none")] pub prepare_support: Option<bool>, /// Client supports the default behavior result. /// /// The value indicates the default behavior used by the /// client. /// /// since 3.16.0 #[serde(skip_serializing_if = "Option::is_none")] pub prepare_support_default_behavior: Option<PrepareSupportDefaultBehavior>, /// Whether the client honors the change annotations in /// text edits and resource operations returned via the /// rename request's workspace edit by for example presenting /// the workspace edit in the user interface and asking /// for confirmation. /// /// @since 3.16.0 #[serde(skip_serializing_if = "Option::is_none")] pub honors_change_annotations: Option<bool>, } #[derive(Debug, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)] #[serde(transparent)] pub struct PrepareSupportDefaultBehavior(i32); impl PrepareSupportDefaultBehavior { /// The client's default behavior is to select the identifier /// according the to language's syntax rule pub const IDENTIFIER: PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior(1); } #[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)] #[serde(untagged)] #[serde(rename_all = "camelCase")] pub enum PrepareRenameResponse { Range(Range), RangeWithPlaceholder { range: Range, placeholder: String, }, #[serde(rename_all = "camelCase")] DefaultBehavior { default_behavior: bool, }, }
RenameParams
search_space_1.py
import itertools import matplotlib.pyplot as plt import numpy as np from nasbench import api from naslib.search_spaces.nasbench1shot1.search_space import SearchSpace from naslib.search_spaces.nasbench1shot1.utils import upscale_to_nasbench_format, OUTPUT_NODE, INPUT, CONV1X1, OUTPUT from naslib.search_spaces.nasbench1shot1.wrappers import Model, Architecture, NasbenchWrapper class SearchSpace1(SearchSpace): def
(self): super(SearchSpace1, self).__init__(search_space_number=1, num_intermediate_nodes=4) """ SEARCH SPACE 1 """ self.num_parents_per_node = { '0': 0, '1': 1, '2': 2, '3': 2, '4': 2, '5': 2 } if sum(self.num_parents_per_node.values()) > 9: raise ValueError('Each nasbench cell has at most 9 edges.') self.test_min_error = 0.05448716878890991 self.valid_min_error = 0.049278855323791504 def create_nasbench_adjacency_matrix(self, parents, **kwargs): adjacency_matrix = self._create_adjacency_matrix(parents, adjacency_matrix=np.zeros([6, 6]), node=OUTPUT_NODE - 1) # Create nasbench compatible adjacency matrix return upscale_to_nasbench_format(adjacency_matrix) def create_nasbench_adjacency_matrix_with_loose_ends(self, parents): return upscale_to_nasbench_format(self._create_adjacency_matrix_with_loose_ends(parents)) def generate_adjacency_matrix_without_loose_ends(self): for adjacency_matrix in self._generate_adjacency_matrix(adjacency_matrix=np.zeros([6, 6]), node=OUTPUT_NODE - 1): yield upscale_to_nasbench_format(adjacency_matrix) def objective_function(self, nasbench, config, budget=108): adjacency_matrix, node_list = super(SearchSpace1, self).convert_config_to_nasbench_format(config) # adjacency_matrix = upscale_to_nasbench_format(adjacency_matrix) node_list = [INPUT, *node_list, CONV1X1, OUTPUT] adjacency_list = adjacency_matrix.astype(np.int).tolist() model_spec = api.ModelSpec(matrix=adjacency_list, ops=node_list) nasbench_data = nasbench.query(model_spec, epochs=budget) # record the data to history architecture = Model() arch = Architecture(adjacency_matrix=adjacency_matrix, node_list=node_list) architecture.update_data(arch, nasbench_data, budget) self.run_history.append(architecture) return nasbench_data['validation_accuracy'], nasbench_data['training_time'] def generate_with_loose_ends(self): for _, parent_node_3, parent_node_4, output_parents in itertools.product( *[itertools.combinations(list(range(int(node))), num_parents) for node, num_parents in self.num_parents_per_node.items()][2:]): parents = { '0': [], '1': [0], '2': [0, 1], '3': parent_node_3, '4': parent_node_4, '5': output_parents } adjacency_matrix = self.create_nasbench_adjacency_matrix_with_loose_ends(parents) yield adjacency_matrix
__init__
structs.go
package model import ( "strconv" "strings" "unicode" "github.com/docker/docker/api/types/swarm" ) type Resources struct { NanoCPUs int64 MemoryBytes int64 } func (r Resources) ToNormalCPU() float64 { return float64(r.NanoCPUs) / 1e+9 } // ServiceMetrics contains all service metrics for easy exporting type ServiceMetrics struct { Name string ServiceMode string Container string Limits Resources Reservation Resources TimeCreated int64 TimeUpdated int64 Replicas float64 } // NodeMetrics contains all node metrics for easy exporting type NodeMetrics struct { ID string Host string Role swarm.NodeRole Os string Architecture string Availability string EngineVersion string NodeStatus string Resources Resources ManagerInfo managerInfo } type managerInfo struct { Reachability string Leader bool } // ManagerReachability get the manager reachability if ManagerInfo != nil func (nm NodeMetrics) ManagerReachability() string { if nm.ManagerInfo == (managerInfo{}) { return string(swarm.ReachabilityUnknown) } return string(nm.ManagerInfo.Reachability) } // IsLeader get the bool if a node is a manager, if ManagerInfo != nil func (nm NodeMetrics) IsLeader() string { if nm.ManagerInfo == (managerInfo{}) { return "false" } return strconv.FormatBool(nm.ManagerInfo.Leader) } // SwarmMetrics contains generic swarm metrics type SwarmMetrics struct { ID string Container ContainerMetrics NCPU int Memory int64 Images int } // GetSanitizedID sanitizes the swarm id func (sm SwarmMetrics) GetSanitizedID() string { id := strings.Map(sanitizeRune, sm.ID) return id } // copied from: https://github.com/census-instrumentation/opencensus-go/blob/master/internal/sanitize.go // unable to reuse to to restrictions on 'internal' packages func sanitizeRune(r rune) rune {
// Everything else turns into an underscore return '_' } // ContainerMetrics holds the counts for serveral container states type ContainerMetrics struct { Running int Paused int Stopped int }
if unicode.IsLetter(r) || unicode.IsDigit(r) { return r }
api_op_UntagResource.go
// Code generated by smithy-go-codegen DO NOT EDIT. package kms import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" smithy "github.com/awslabs/smithy-go" "github.com/awslabs/smithy-go/middleware" smithyhttp "github.com/awslabs/smithy-go/transport/http" ) // Removes the specified tags from the specified customer master key (CMK). You // cannot perform this operation on a CMK in a different AWS account. To remove a // tag, specify the tag key. To change the tag value of an existing tag key, use // TagResource (). The CMK that you use for this operation must be in a compatible // key state. For details, see How Key State Affects Use of a Customer Master Key // (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) in the // AWS Key Management Service Developer Guide. func (c *Client) UntagResource(ctx context.Context, params *UntagResourceInput, optFns ...func(*Options)) (*UntagResourceOutput, error) { stack := middleware.NewStack("UntagResource", smithyhttp.NewStackRequest) options := c.options.Copy() for _, fn := range optFns { fn(&options) } addawsAwsjson11_serdeOpUntagResourceMiddlewares(stack) awsmiddleware.AddRequestInvocationIDMiddleware(stack) smithyhttp.AddContentLengthMiddleware(stack) addResolveEndpointMiddleware(stack, options) v4.AddComputePayloadSHA256Middleware(stack) addRetryMiddlewares(stack, options) addHTTPSignerV4Middleware(stack, options) awsmiddleware.AddAttemptClockSkewMiddleware(stack) addClientUserAgent(stack) smithyhttp.AddErrorCloseResponseBodyMiddleware(stack) smithyhttp.AddCloseResponseBodyMiddleware(stack) addOpUntagResourceValidationMiddleware(stack) stack.Initialize.Add(newServiceMetadataMiddleware_opUntagResource(options.Region), middleware.Before) addRequestIDRetrieverMiddleware(stack) addResponseErrorMiddleware(stack) for _, fn := range options.APIOptions { if err := fn(stack); err != nil { return nil, err } } handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) result, metadata, err := handler.Handle(ctx, params) if err != nil { return nil, &smithy.OperationError{ ServiceID: ServiceID, OperationName: "UntagResource", Err: err, } } out := result.(*UntagResourceOutput) out.ResultMetadata = metadata return out, nil } type UntagResourceInput struct { // A unique identifier for the CMK from which you are removing tags. <p>Specify // the key ID or the Amazon Resource Name (ARN) of the CMK.</p> <p>For example:</p> // <ul> <li> <p>Key ID: <code>1234abcd-12ab-34cd-56ef-1234567890ab</code> </p> // </li> <li> <p>Key ARN: // <code>arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab</code> // </p> </li> </ul> <p>To get the key ID and key ARN for a CMK, use <a>ListKeys</a> // or <a>DescribeKey</a>.</p> // // This member is required. KeyId *string // One or more tag keys. Specify only the tag keys, not the tag values. // // This member is required. TagKeys []*string } type UntagResourceOutput struct { // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func
(stack *middleware.Stack) { stack.Serialize.Add(&awsAwsjson11_serializeOpUntagResource{}, middleware.After) stack.Deserialize.Add(&awsAwsjson11_deserializeOpUntagResource{}, middleware.After) } func newServiceMetadataMiddleware_opUntagResource(region string) awsmiddleware.RegisterServiceMetadata { return awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "kms", OperationName: "UntagResource", } }
addawsAwsjson11_serdeOpUntagResourceMiddlewares
khpi.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-khpi', templateUrl: './khpi.component.html', styleUrls: ['./khpi.component.css'] }) export class
implements OnInit { constructor() { } ngOnInit() { } }
KhpiComponent
fusion.go
/* * Copyright 2014 VMware, Inc. All rights reserved. Licensed under the Apache v2 License. */ package vmwarefusion import ( "archive/tar" "bytes" "fmt" "io/ioutil" "net" "os" "regexp" "runtime" "strings" "text/template" "time" "github.com/docker/machine/libmachine/drivers" "github.com/docker/machine/libmachine/log" "github.com/docker/machine/libmachine/mcnflag" "github.com/docker/machine/libmachine/mcnutils" "github.com/docker/machine/libmachine/ssh" "github.com/docker/machine/libmachine/state" cryptossh "golang.org/x/crypto/ssh" ) const ( B2DUser = "docker" B2DPass = "tcuser" isoFilename = "boot2docker.iso" isoConfigDrive = "configdrive.iso" ) // Driver for VMware Fusion type Driver struct { *drivers.BaseDriver Memory int DiskSize int CPU int ISO string Boot2DockerURL string CPUS int SSHPassword string ConfigDriveISO string ConfigDriveURL string NoShare bool } const ( defaultSSHUser = B2DUser defaultSSHPass = B2DPass defaultDiskSize = 20000 defaultCpus = 1 defaultMemory = 1024 ) // GetCreateFlags registers the flags this driver adds to // "docker hosts create" func (d *Driver) GetCreateFlags() []mcnflag.Flag { return []mcnflag.Flag{ mcnflag.StringFlag{ EnvVar: "FUSION_BOOT2DOCKER_URL", Name: "vmwarefusion-boot2docker-url", Usage: "Fusion URL for boot2docker image", Value: "", }, mcnflag.StringFlag{ EnvVar: "FUSION_CONFIGDRIVE_URL", Name: "vmwarefusion-configdrive-url", Usage: "Fusion URL for cloud-init configdrive", Value: "", }, mcnflag.IntFlag{ EnvVar: "FUSION_CPU_COUNT", Name: "vmwarefusion-cpu-count", Usage: "number of CPUs for the machine (-1 to use the number of CPUs available)", Value: defaultCpus, }, mcnflag.IntFlag{ EnvVar: "FUSION_MEMORY_SIZE", Name: "vmwarefusion-memory-size", Usage: "Fusion size of memory for host VM (in MB)", Value: defaultMemory, }, mcnflag.IntFlag{ EnvVar: "FUSION_DISK_SIZE", Name: "vmwarefusion-disk-size", Usage: "Fusion size of disk for host VM (in MB)", Value: defaultDiskSize, }, mcnflag.StringFlag{ EnvVar: "FUSION_SSH_USER", Name: "vmwarefusion-ssh-user", Usage: "SSH user", Value: defaultSSHUser, }, mcnflag.StringFlag{ EnvVar: "FUSION_SSH_PASSWORD", Name: "vmwarefusion-ssh-password", Usage: "SSH password", Value: defaultSSHPass, }, mcnflag.BoolFlag{ EnvVar: "FUSION_NO_SHARE", Name: "vmwarefusion-no-share", Usage: "Disable the mount of your home directory", }, } } func NewDriver(hostName, storePath string) drivers.Driver { return &Driver{ CPUS: defaultCpus, Memory: defaultMemory, DiskSize: defaultDiskSize, SSHPassword: defaultSSHPass, BaseDriver: &drivers.BaseDriver{ SSHUser: defaultSSHUser, MachineName: hostName, StorePath: storePath, }, } } func (d *Driver) GetSSHHostname() (string, error) { return d.GetIP() } func (d *Driver) GetSSHUsername() string { if d.SSHUser == "" { d.SSHUser = "docker" } return d.SSHUser } // DriverName returns the name of the driver func (d *Driver) DriverName() string { return "vmwarefusion" } func (d *Driver) SetConfigFromFlags(flags drivers.DriverOptions) error { d.Memory = flags.Int("vmwarefusion-memory-size") d.CPU = flags.Int("vmwarefusion-cpu-count") d.DiskSize = flags.Int("vmwarefusion-disk-size") d.Boot2DockerURL = flags.String("vmwarefusion-boot2docker-url") d.ConfigDriveURL = flags.String("vmwarefusion-configdrive-url") d.ISO = d.ResolveStorePath(isoFilename) d.ConfigDriveISO = d.ResolveStorePath(isoConfigDrive) d.SwarmMaster = flags.Bool("swarm-master") d.SwarmHost = flags.String("swarm-host") d.SwarmDiscovery = flags.String("swarm-discovery") d.SSHUser = flags.String("vmwarefusion-ssh-user") d.SSHPassword = flags.String("vmwarefusion-ssh-password") d.SSHPort = 22 d.NoShare = flags.Bool("vmwarefusion-no-share") // We support a maximum of 16 cpu to be consistent with Virtual Hardware 10 // specs. if d.CPU < 1 { d.CPU = int(runtime.NumCPU()) } if d.CPU > 16 { d.CPU = 16 } return nil } func (d *Driver) GetURL() (string, error) { ip, err := d.GetIP() if err != nil { return "", err } if ip == "" { return "", nil } return fmt.Sprintf("tcp://%s", net.JoinHostPort(ip, "2376")), nil } func (d *Driver) GetIP() (string, error) { s, err := d.GetState() if err != nil { return "", err } if s != state.Running { return "", drivers.ErrHostIsNotRunning } ip, err := d.getIPfromDHCPLease() if err != nil { return "", err } return ip, nil } func (d *Driver) GetState() (state.State, error) { // VMRUN only tells use if the vm is running or not if stdout, _, _ := vmrun("list"); strings.Contains(stdout, d.vmxPath()) { return state.Running, nil } return state.Stopped, nil } func (d *Driver) Create() error { b2dutils := mcnutils.NewB2dUtils(d.StorePath) if err := b2dutils.CopyIsoToMachineDir(d.Boot2DockerURL, d.MachineName); err != nil { return err } // download cloud-init config drive if d.ConfigDriveURL != "" { log.Infof("Downloading %s from %s", isoConfigDrive, d.ConfigDriveURL) if err := b2dutils.DownloadISO(d.ResolveStorePath("."), isoConfigDrive, d.ConfigDriveURL); err != nil { return err } } log.Infof("Creating SSH key...") if err := ssh.GenerateSSHKey(d.GetSSHKeyPath()); err != nil { return err } log.Infof("Creating VM...") if err := os.MkdirAll(d.ResolveStorePath("."), 0755); err != nil { return err } if _, err := os.Stat(d.vmxPath()); err == nil { return ErrMachineExist } // Generate vmx config file from template vmxt := template.Must(template.New("vmx").Parse(vmx)) vmxfile, err := os.Create(d.vmxPath()) if err != nil { return err } vmxt.Execute(vmxfile, d) // Generate vmdk file diskImg := d.ResolveStorePath(fmt.Sprintf("%s.vmdk", d.MachineName)) if _, err := os.Stat(diskImg); err != nil { if !os.IsNotExist(err) { return err } if err := vdiskmanager(diskImg, d.DiskSize); err != nil { return err } } log.Infof("Starting %s...", d.MachineName) vmrun("start", d.vmxPath(), "nogui") var ip string log.Infof("Waiting for VM to come online...") for i := 1; i <= 60; i++ { ip, err = d.getIPfromDHCPLease() if err != nil { log.Debugf("Not there yet %d/%d, error: %s", i, 60, err) time.Sleep(2 * time.Second) continue } if ip != "" { log.Debugf("Got an ip: %s", ip) conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", ip, 22), time.Duration(2*time.Second)) if err != nil { log.Debugf("SSH Daemon not responding yet: %s", err) time.Sleep(2 * time.Second) continue } conn.Close() break } } if ip == "" { return fmt.Errorf("Machine didn't return an IP after 120 seconds, aborting") } // we got an IP, let's copy ssh keys over d.IPAddress = ip // Do not execute the rest of boot2docker specific configuration // The uplaod of the public ssh key uses a ssh connection, // this works without installed vmware client tools if d.ConfigDriveURL != "" { var keyfh *os.File var keycontent []byte log.Infof("Copy public SSH key to %s [%s]", d.MachineName, d.IPAddress) // create .ssh folder in users home if err := executeSSHCommand(fmt.Sprintf("mkdir -p /home/%s/.ssh", d.SSHUser), d); err != nil { return err } // read generated public ssh key if keyfh, err = os.Open(d.publicSSHKeyPath()); err != nil { return err } defer keyfh.Close() if keycontent, err = ioutil.ReadAll(keyfh); err != nil { return err } // add public ssh key to authorized_keys if err := executeSSHCommand(fmt.Sprintf("echo '%s' > /home/%s/.ssh/authorized_keys", string(keycontent), d.SSHUser), d); err != nil { return err } // make it secure if err := executeSSHCommand(fmt.Sprintf("chmod 600 /home/%s/.ssh/authorized_keys", d.SSHUser), d); err != nil { return err } log.Debugf("Leaving create sequence early, configdrive found") return nil } // Generate a tar keys bundle if err := d.generateKeyBundle(); err != nil { return err } // Test if /var/lib/boot2docker exists vmrun("-gu", B2DUser, "-gp", B2DPass, "directoryExistsInGuest", d.vmxPath(), "/var/lib/boot2docker") // Copy SSH keys bundle vmrun("-gu", B2DUser, "-gp", B2DPass, "CopyFileFromHostToGuest", d.vmxPath(), d.ResolveStorePath("userdata.tar"), "/home/docker/userdata.tar") // Expand tar file. vmrun("-gu", B2DUser, "-gp", B2DPass, "runScriptInGuest", d.vmxPath(), "/bin/sh", "sudo /bin/mv /home/docker/userdata.tar /var/lib/boot2docker/userdata.tar && sudo tar xf /var/lib/boot2docker/userdata.tar -C /home/docker/ > /var/log/userdata.log 2>&1 && sudo chown -R docker:staff /home/docker") // Enable Shared Folders vmrun("-gu", B2DUser, "-gp", B2DPass, "enableSharedFolders", d.vmxPath()) var shareName, shareDir string // TODO configurable at some point switch runtime.GOOS { case "darwin": shareName = "Users" shareDir = "/Users" // TODO "linux" and "windows" } if shareDir != "" && !d.NoShare { if _, err := os.Stat(shareDir); err != nil && !os.IsNotExist(err) { return err } else if !os.IsNotExist(err) { // add shared folder, create mountpoint and mount it. vmrun("-gu", B2DUser, "-gp", B2DPass, "addSharedFolder", d.vmxPath(), shareName, shareDir) command := "[ ! -d " + shareDir + " ]&& sudo mkdir " + shareDir + "; [ -f /usr/local/bin/vmhgfs-fuse ]&& sudo /usr/local/bin/vmhgfs-fuse -o allow_other .host:/" + shareName + " " + shareDir + " || sudo mount -t vmhgfs -o uid=$(id -u),gid=$(id -g) .host:/" + shareName + " " + shareDir vmrun("-gu", B2DUser, "-gp", B2DPass, "runScriptInGuest", d.vmxPath(), "/bin/sh", command) } } return nil } func (d *Driver) Start() error { log.Infof("Starting %s...", d.MachineName) vmrun("start", d.vmxPath(), "nogui") // Do not execute the rest of boot2docker specific configuration, exit here if d.ConfigDriveURL != "" { log.Debugf("Leaving start sequence early, configdrive found") return nil } log.Debugf("Mounting Shared Folders...") var shareName, shareDir string // TODO configurable at some point switch runtime.GOOS { case "darwin": shareName = "Users" shareDir = "/Users" // TODO "linux" and "windows" } if shareDir != "" { if _, err := os.Stat(shareDir); err != nil && !os.IsNotExist(err) { return err } else if !os.IsNotExist(err) { // create mountpoint and mount shared folder command := "[ ! -d " + shareDir + " ]&& sudo mkdir " + shareDir + "; [ -f /usr/local/bin/vmhgfs-fuse ]&& sudo /usr/local/bin/vmhgfs-fuse -o allow_other .host:/" + shareName + " " + shareDir + " || sudo mount -t vmhgfs -o uid=$(id -u),gid=$(id -g) .host:/" + shareName + " " + shareDir vmrun("-gu", B2DUser, "-gp", B2DPass, "runScriptInGuest", d.vmxPath(), "/bin/sh", command) } } return nil } func (d *Driver) Stop() error { log.Infof("Gracefully shutting down %s...", d.MachineName) vmrun("stop", d.vmxPath(), "nogui") return nil } func (d *Driver) Remove() error { s, _ := d.GetState() if s == state.Running { if err := d.Kill(); err != nil { return fmt.Errorf("Error stopping VM before deletion") } } log.Infof("Deleting %s...", d.MachineName) vmrun("deleteVM", d.vmxPath(), "nogui") return nil } func (d *Driver) Restart() error { log.Infof("Gracefully restarting %s...", d.MachineName) vmrun("reset", d.vmxPath(), "nogui") return nil } func (d *Driver) Kill() error { log.Infof("Forcibly halting %s...", d.MachineName) vmrun("stop", d.vmxPath(), "hard nogui") return nil } func (d *Driver) Upgrade() error { return fmt.Errorf("VMware Fusion does not currently support the upgrade operation") } func (d *Driver) vmxPath() string { return d.ResolveStorePath(fmt.Sprintf("%s.vmx", d.MachineName)) } func (d *Driver) vmdkPath() string { return d.ResolveStorePath(fmt.Sprintf("%s.vmdk", d.MachineName)) } func (d *Driver) getIPfromDHCPLease() (string, error) { var vmxfh *os.File var dhcpfh *os.File var vmxcontent []byte var dhcpcontent []byte var macaddr string var err error var lastipmatch string var currentip string var lastleaseendtime time.Time var currentleadeendtime time.Time // DHCP lease table for NAT vmnet interface var dhcpfile = "/var/db/vmware/vmnet-dhcpd-vmnet8.leases" if vmxfh, err = os.Open(d.vmxPath()); err != nil { return "", err } defer vmxfh.Close() if vmxcontent, err = ioutil.ReadAll(vmxfh); err != nil { return "", err } // Look for generatedAddress as we're passing a VMX with addressType = "generated". vmxparse := regexp.MustCompile(`^ethernet0.generatedAddress\s*=\s*"(.*?)"\s*$`) for _, line := range strings.Split(string(vmxcontent), "\n") { if matches := vmxparse.FindStringSubmatch(line); matches == nil { continue } else { macaddr = strings.ToLower(matches[1]) } } if macaddr == "" { return "", fmt.Errorf("couldn't find MAC address in VMX file %s", d.vmxPath())
} log.Debugf("MAC address in VMX: %s", macaddr) if dhcpfh, err = os.Open(dhcpfile); err != nil { return "", err } defer dhcpfh.Close() if dhcpcontent, err = ioutil.ReadAll(dhcpfh); err != nil { return "", err } // Get the IP from the lease table. leaseip := regexp.MustCompile(`^lease (.+?) {$`) // Get the lease end date time. leaseend := regexp.MustCompile(`^\s*ends \d (.+?);$`) // Get the MAC address associated. leasemac := regexp.MustCompile(`^\s*hardware ethernet (.+?);$`) for _, line := range strings.Split(string(dhcpcontent), "\n") { if matches := leaseip.FindStringSubmatch(line); matches != nil { lastipmatch = matches[1] continue } if matches := leaseend.FindStringSubmatch(line); matches != nil { lastleaseendtime, _ = time.Parse("2006/01/02 15:04:05", matches[1]) continue } if matches := leasemac.FindStringSubmatch(line); matches != nil && matches[1] == macaddr && currentleadeendtime.Before(lastleaseendtime) { currentip = lastipmatch currentleadeendtime = lastleaseendtime } } if currentip == "" { return "", fmt.Errorf("IP not found for MAC %s in DHCP leases", macaddr) } log.Debugf("IP found in DHCP lease table: %s", currentip) return currentip, nil } func (d *Driver) publicSSHKeyPath() string { return d.GetSSHKeyPath() + ".pub" } // Make a boot2docker userdata.tar key bundle func (d *Driver) generateKeyBundle() error { log.Debugf("Creating Tar key bundle...") magicString := "boot2docker, this is vmware speaking" tf, err := os.Create(d.ResolveStorePath("userdata.tar")) if err != nil { return err } defer tf.Close() var fileWriter = tf tw := tar.NewWriter(fileWriter) defer tw.Close() // magicString first so we can figure out who originally wrote the tar. file := &tar.Header{Name: magicString, Size: int64(len(magicString))} if err := tw.WriteHeader(file); err != nil { return err } if _, err := tw.Write([]byte(magicString)); err != nil { return err } // .ssh/key.pub => authorized_keys file = &tar.Header{Name: ".ssh", Typeflag: tar.TypeDir, Mode: 0700} if err := tw.WriteHeader(file); err != nil { return err } pubKey, err := ioutil.ReadFile(d.publicSSHKeyPath()) if err != nil { return err } file = &tar.Header{Name: ".ssh/authorized_keys", Size: int64(len(pubKey)), Mode: 0644} if err := tw.WriteHeader(file); err != nil { return err } if _, err := tw.Write([]byte(pubKey)); err != nil { return err } file = &tar.Header{Name: ".ssh/authorized_keys2", Size: int64(len(pubKey)), Mode: 0644} if err := tw.WriteHeader(file); err != nil { return err } if _, err := tw.Write([]byte(pubKey)); err != nil { return err } if err := tw.Close(); err != nil { return err } return nil } // execute command over SSH with user / password authentication func executeSSHCommand(command string, d *Driver) error { log.Debugf("Execute executeSSHCommand: %s", command) config := &cryptossh.ClientConfig{ User: d.SSHUser, Auth: []cryptossh.AuthMethod{ cryptossh.Password(d.SSHPassword), }, } client, err := cryptossh.Dial("tcp", fmt.Sprintf("%s:%d", d.IPAddress, d.SSHPort), config) if err != nil { log.Debugf("Failed to dial:", err) return err } session, err := client.NewSession() if err != nil { log.Debugf("Failed to create session: " + err.Error()) return err } defer session.Close() var b bytes.Buffer session.Stdout = &b if err := session.Run(command); err != nil { log.Debugf("Failed to run: " + err.Error()) return err } log.Debugf("Stdout from executeSSHCommand: %s", b.String()) return nil }
space_descriptor.rs
use super::vmrequest::HEAP_LAYOUT_64BIT; use crate::util::constants::*; #[cfg(target_pointer_width = "64")] use crate::util::heap::layout::heap_parameters; use crate::util::heap::layout::vm_layout_constants; use crate::util::Address; use std::sync::atomic::{AtomicUsize, Ordering}; const TYPE_BITS: usize = 2; #[allow(unused)] const TYPE_SHARED: usize = 0; const TYPE_CONTIGUOUS: usize = 1; const TYPE_CONTIGUOUS_HI: usize = 3; const TYPE_MASK: usize = (1 << TYPE_BITS) - 1; const SIZE_SHIFT: usize = TYPE_BITS; const SIZE_BITS: usize = 10; const SIZE_MASK: usize = ((1 << SIZE_BITS) - 1) << SIZE_SHIFT; const EXPONENT_SHIFT: usize = SIZE_SHIFT + SIZE_BITS; const EXPONENT_BITS: usize = 5; #[cfg(target_pointer_width = "32")] const EXPONENT_MASK: usize = ((1 << EXPONENT_BITS) - 1) << EXPONENT_SHIFT; const MANTISSA_SHIFT: usize = EXPONENT_SHIFT + EXPONENT_BITS; const MANTISSA_BITS: usize = 14; const BASE_EXPONENT: usize = BITS_IN_INT - MANTISSA_BITS; /* 64-bit */ const INDEX_MASK: usize = !TYPE_MASK; const INDEX_SHIFT: usize = TYPE_BITS; static DISCONTIGUOUS_SPACE_INDEX: AtomicUsize = AtomicUsize::new(0); const DISCONTIG_INDEX_INCREMENT: usize = 1 << TYPE_BITS; #[derive(Copy, Clone, PartialEq, Debug)] pub struct SpaceDescriptor(usize); impl SpaceDescriptor { pub const UNINITIALIZED: Self = SpaceDescriptor(0); pub fn create_descriptor_from_heap_range(start: Address, end: Address) -> SpaceDescriptor { let top = end == vm_layout_constants::HEAP_END; if HEAP_LAYOUT_64BIT { let space_index = if start > vm_layout_constants::HEAP_END { ::std::usize::MAX } else { start >> vm_layout_constants::SPACE_SHIFT_64 }; return SpaceDescriptor( space_index << INDEX_SHIFT | (if top { TYPE_CONTIGUOUS_HI } else { TYPE_CONTIGUOUS }), ); } let chunks = (end - start) >> vm_layout_constants::LOG_BYTES_IN_CHUNK; if cfg!(debug) { // if (!start.isZero() && (chunks <= 0 || chunks >= (1 << SIZE_BITS))) { // Log.write("SpaceDescriptor.createDescriptor(", start); // Log.write(",", end); // Log.writeln(")"); // Log.writeln("chunks = ", chunks); // } debug_assert!(!start.is_zero() && chunks > 0 && chunks < (1 << SIZE_BITS)); } let mut tmp = start >> BASE_EXPONENT; let mut exponent = 0; while (tmp != 0) && ((tmp & 1) == 0) { tmp >>= 1; exponent += 1; } let mantissa = tmp; debug_assert!((tmp << (BASE_EXPONENT + exponent)) == start.as_usize()); SpaceDescriptor( (mantissa << MANTISSA_SHIFT) | (exponent << EXPONENT_SHIFT) | (chunks << SIZE_SHIFT) | (if top { TYPE_CONTIGUOUS_HI } else { TYPE_CONTIGUOUS }), ) } pub fn create_descriptor() -> SpaceDescriptor
pub fn is_empty(self) -> bool { self.0 == SpaceDescriptor::UNINITIALIZED.0 } pub fn is_contiguous(self) -> bool { (self.0 & TYPE_CONTIGUOUS) == TYPE_CONTIGUOUS } pub fn is_contiguous_hi(self) -> bool { (self.0 & TYPE_MASK) == TYPE_CONTIGUOUS_HI } #[cfg(target_pointer_width = "64")] pub fn get_start(self) -> Address { unsafe { Address::from_usize(self.get_index() << heap_parameters::LOG_SPACE_SIZE_64) } } #[cfg(target_pointer_width = "32")] pub fn get_start(self) -> Address { debug_assert!(self.is_contiguous()); let descriptor = self.0; let mantissa = descriptor >> MANTISSA_SHIFT; let exponent = (descriptor & EXPONENT_MASK) >> EXPONENT_SHIFT; unsafe { Address::from_usize(mantissa << (BASE_EXPONENT + exponent)) } } pub fn get_extent(self) -> usize { if HEAP_LAYOUT_64BIT { return vm_layout_constants::SPACE_SIZE_64; } debug_assert!(self.is_contiguous()); let chunks = (self.0 & SIZE_MASK) >> SIZE_SHIFT; chunks << vm_layout_constants::LOG_BYTES_IN_CHUNK } // FIXME: This function should only work for 64 bit heap. // However, HEAP_LAYOUT_64BIT is a constant at the moment (which is not correct), and // we do want this function failed the assertion if HEAP_LAYOUT_64BIT is no longer constantly true. #[allow(clippy::assertions_on_constants)] pub fn get_index(self) -> usize { debug_assert!(HEAP_LAYOUT_64BIT); (self.0 & INDEX_MASK) >> INDEX_SHIFT } }
{ let next = DISCONTIGUOUS_SPACE_INDEX.fetch_add(DISCONTIG_INDEX_INCREMENT, Ordering::Relaxed); let ret = SpaceDescriptor(next); debug_assert!(!ret.is_contiguous()); ret }
config.go
// Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package model import ( "errors" "fmt" "sort" "strings" "github.com/golang/protobuf/proto" authn "istio.io/api/authentication/v1alpha1" mccpb "istio.io/api/mixer/v1/config/client" networking "istio.io/api/networking/v1alpha3" routing "istio.io/api/routing/v1alpha1" "istio.io/istio/pilot/pkg/model/test" "istio.io/istio/pkg/log" ) // ConfigMeta is metadata attached to each configuration unit. // The revision is optional, and if provided, identifies the // last update operation on the object. type ConfigMeta struct { // Type is a short configuration name that matches the content message type // (e.g. "route-rule") Type string `json:"type,omitempty"` // Group is the API group of the config. Group string `json:"group,omitempty"` // Version is the API version of the Config. Version string `json:"version,omitempty"` // Name is a unique immutable identifier in a namespace Name string `json:"name,omitempty"` // Namespace defines the space for names (optional for some types), // applications may choose to use namespaces for a variety of purposes // (security domains, fault domains, organizational domains) Namespace string `json:"namespace,omitempty"` // Domain defines the suffix of the fully qualified name past the namespace. // Domain is not a part of the unique key unlike name and namespace. Domain string `json:"domain,omitempty"` // Map of string keys and values that can be used to organize and categorize // (scope and select) objects. Labels map[string]string `json:"labels,omitempty"` // Annotations is an unstructured key value map stored with a resource that may be // set by external tools to store and retrieve arbitrary metadata. They are not // queryable and should be preserved when modifying objects. Annotations map[string]string `json:"annotations,omitempty"` // ResourceVersion is an opaque identifier for tracking updates to the config registry. // The implementation may use a change index or a commit log for the revision. // The config client should not make any assumptions about revisions and rely only on // exact equality to implement optimistic concurrency of read-write operations. // // The lifetime of an object of a particular revision depends on the underlying data store. // The data store may compactify old revisions in the interest of storage optimization. // // An empty revision carries a special meaning that the associated object has // not been stored and assigned a revision. ResourceVersion string `json:"resourceVersion,omitempty"` } // Config is a configuration unit consisting of the type of configuration, the // key identifier that is unique per type, and the content represented as a // protobuf message. type Config struct { ConfigMeta // Spec holds the configuration object as a protobuf message Spec proto.Message } // ConfigStore describes a set of platform agnostic APIs that must be supported // by the underlying platform to store and retrieve Istio configuration. // // Configuration key is defined to be a combination of the type, name, and // namespace of the configuration object. The configuration key is guaranteed // to be unique in the store. // // The storage interface presented here assumes that the underlying storage // layer supports _Get_ (list), _Update_ (update), _Create_ (create) and // _Delete_ semantics but does not guarantee any transactional semantics. // // _Update_, _Create_, and _Delete_ are mutator operations. These operations // are asynchronous, and you might not see the effect immediately (e.g. _Get_ // might not return the object by key immediately after you mutate the store.) // Intermittent errors might occur even though the operation succeeds, so you // should always check if the object store has been modified even if the // mutating operation returns an error. Objects should be created with // _Create_ operation and updated with _Update_ operation. // // Resource versions record the last mutation operation on each object. If a // mutation is applied to a different revision of an object than what the // underlying storage expects as defined by pure equality, the operation is // blocked. The client of this interface should not make assumptions about the // structure or ordering of the revision identifier. // // Object references supplied and returned from this interface should be // treated as read-only. Modifying them violates thread-safety. type ConfigStore interface { // ConfigDescriptor exposes the configuration type schema known by the config store. // The type schema defines the bidrectional mapping between configuration // types and the protobuf encoding schema. ConfigDescriptor() ConfigDescriptor // Get retrieves a configuration element by a type and a key Get(typ, name, namespace string) (config *Config, exists bool) // List returns objects by type and namespace. // Use "" for the namespace to list across namespaces. List(typ, namespace string) ([]Config, error) // Create adds a new configuration object to the store. If an object with the // same name and namespace for the type already exists, the operation fails // with no side effects. Create(config Config) (revision string, err error) // Update modifies an existing configuration object in the store. Update // requires that the object has been created. Resource version prevents // overriding a value that has been changed between prior _Get_ and _Put_ // operation to achieve optimistic concurrency. This method returns a new // revision if the operation succeeds. Update(config Config) (newRevision string, err error) // Delete removes an object from the store by key Delete(typ, name, namespace string) error } // Key function for the configuration objects func Key(typ, name, namespace string) string { return fmt.Sprintf("%s/%s/%s", typ, namespace, name) } // Key is the unique identifier for a configuration object func (meta *ConfigMeta) Key() string { return Key(meta.Type, meta.Name, meta.Namespace) } // ConfigStoreCache is a local fully-replicated cache of the config store. The // cache actively synchronizes its local state with the remote store and // provides a notification mechanism to receive update events. As such, the // notification handlers must be registered prior to calling _Run_, and the // cache requires initial synchronization grace period after calling _Run_. // // Update notifications require the following consistency guarantee: the view // in the cache must be AT LEAST as fresh as the moment notification arrives, but // MAY BE more fresh (e.g. if _Delete_ cancels an _Add_ event). // // Handlers execute on the single worker queue in the order they are appended. // Handlers receive the notification event and the associated object. Note // that all handlers must be registered before starting the cache controller. type ConfigStoreCache interface { ConfigStore // RegisterEventHandler adds a handler to receive config update events for a // configuration type RegisterEventHandler(typ string, handler func(Config, Event)) // Run until a signal is received Run(stop <-chan struct{}) // HasSynced returns true after initial cache synchronization is complete HasSynced() bool } // ConfigDescriptor defines the bijection between the short type name and its // fully qualified protobuf message name type ConfigDescriptor []ProtoSchema // ProtoSchema provides description of the configuration schema and its key function type ProtoSchema struct { // Type is the config proto type. Type string // Plural is the type in plural. Plural string // Group is the config proto group. Group string // Version is the config proto version. Version string // MessageName refers to the protobuf message type name corresponding to the type MessageName string // Gogo is true for gogo protobuf messages Gogo bool // Validate configuration as a protobuf message assuming the object is an // instance of the expected message type Validate func(config proto.Message) error } // Types lists all known types in the config schema func (descriptor ConfigDescriptor) Types() []string { types := make([]string, 0, len(descriptor)) for _, t := range descriptor { types = append(types, t.Type) } return types } // GetByMessageName finds a schema by message name if it is available func (descriptor ConfigDescriptor) GetByMessageName(name string) (ProtoSchema, bool) { for _, schema := range descriptor { if schema.MessageName == name { return schema, true } } return ProtoSchema{}, false } // GetByType finds a schema by type if it is available func (descriptor ConfigDescriptor) GetByType(name string) (ProtoSchema, bool) { for _, schema := range descriptor { if schema.Type == name { return schema, true } } return ProtoSchema{}, false } // IstioConfigStore is a specialized interface to access config store using // Istio configuration types type IstioConfigStore interface { ConfigStore // EgressRules lists all egress rules EgressRules() []Config // ServiceEntries lists all service entries ServiceEntries() []Config // RouteRules selects routing rules by source service instances and // destination service. A rule must match at least one of the input service // instances since the proxy does not distinguish between source instances in // the request. RouteRules(source []*ServiceInstance, destination string) []Config // RouteRulesByDestination selects routing rules associated with destination // service instances. A rule must match at least one of the input // destination instances. RouteRulesByDestination(destination []*ServiceInstance) []Config // Policy returns a policy for a service version that match at least one of // the source instances. The labels must match precisely in the policy. Policy(source []*ServiceInstance, destination string, labels Labels) *Config // DestinationRule returns a destination rule for a service name in a given domain. DestinationRule(hostname Hostname) *Config // VirtualServices lists all virtual services bound to the specified gateways VirtualServices(gateways map[string]bool) []Config // Gateways lists all gateways bound to the specified workload labels Gateways(workloadLabels LabelsCollection) []Config // SubsetToLabels returns the labels associated with a subset of a given service. SubsetToLabels(subsetName string, hostname Hostname) LabelsCollection // HTTPAPISpecByDestination selects Mixerclient HTTP API Specs // associated with destination service instances. HTTPAPISpecByDestination(instance *ServiceInstance) []Config // QuotaSpecByDestination selects Mixerclient quota specifications // associated with destination service instances. QuotaSpecByDestination(instance *ServiceInstance) []Config // AuthenticationPolicyByDestination selects authentication policy associated // with a service + port. Hostname must be FQDN. // If there are more than one policies at different scopes (global, namespace, service) // the one with the most specific scope will be selected. If there are more than // one with the same scope, the first one seen will be used (later, we should // have validation at submitting time to prevent this scenario from happening) AuthenticationPolicyByDestination(hostname Hostname, port *Port) *Config } const ( // IstioAPIGroupDomain defines API group domain of all Istio configuration resources. // Group domain suffix to the proto schema's group to generate the full resource group. IstioAPIGroupDomain = ".istio.io" // Default API version of an Istio config proto message. istioAPIVersion = "v1alpha2" // HeaderURI is URI HTTP header HeaderURI = "uri" // HeaderAuthority is authority HTTP header HeaderAuthority = "authority" // HeaderMethod is method HTTP header HeaderMethod = "method" // HeaderScheme is scheme HTTP header HeaderScheme = "scheme" // NamespaceAll is a designated symbol for listing across all namespaces NamespaceAll = "" // IstioMeshGateway is the built in gateway for all sidecars IstioMeshGateway = "mesh" ) /* This conversion of CRD (== yaml files with k8s metadata) is extremely inefficient. The yaml is parsed (kubeyaml), converted to YAML again (FromJSONMap), converted to JSON (YAMLToJSON) and finally UnmarshallString in proto is called. The result is not cached in the model. In 0.7, this was the biggest factor in scalability. Moving forward we will likely deprecate model, and do the conversion (hopefully more efficient) only once, when an object is first read. */ var ( // MockConfig is used purely for testing MockConfig = ProtoSchema{ Type: "mock-config", Plural: "mock-configs", Group: "test", Version: "v1", MessageName: "test.MockConfig", Validate: func(config proto.Message) error { if config.(*test.MockConfig).Key == "" { return errors.New("empty key") } return nil }, } // RouteRule describes route rules RouteRule = ProtoSchema{ Type: "route-rule", Plural: "route-rules", Group: "config", Version: istioAPIVersion, MessageName: "istio.routing.v1alpha1.RouteRule", Validate: ValidateRouteRule, } // VirtualService describes v1alpha3 route rules VirtualService = ProtoSchema{ Type: "virtual-service", Plural: "virtual-services", Group: "networking", Version: "v1alpha3", MessageName: "istio.networking.v1alpha3.VirtualService", Gogo: true, Validate: ValidateVirtualService, } // Gateway describes a gateway (how a proxy is exposed on the network) Gateway = ProtoSchema{ Type: "gateway", Plural: "gateways", Group: "networking", Version: "v1alpha3", MessageName: "istio.networking.v1alpha3.Gateway", Gogo: true, Validate: ValidateGateway, } // IngressRule describes ingress rules IngressRule = ProtoSchema{ Type: "ingress-rule", Plural: "ingress-rules", Group: "config", Version: istioAPIVersion, MessageName: "istio.routing.v1alpha1.IngressRule", Validate: ValidateIngressRule, } // EgressRule describes egress rule EgressRule = ProtoSchema{ Type: "egress-rule", Plural: "egress-rules", Group: "config", Version: istioAPIVersion, MessageName: "istio.routing.v1alpha1.EgressRule", Validate: ValidateEgressRule, } // ServiceEntry describes service entries ServiceEntry = ProtoSchema{ Type: "service-entry", Plural: "service-entries", Group: "networking", Version: "v1alpha3", MessageName: "istio.networking.v1alpha3.ServiceEntry", Gogo: true, Validate: ValidateServiceEntry, } // DestinationPolicy describes destination rules DestinationPolicy = ProtoSchema{ Type: "destination-policy", Plural: "destination-policies", Group: "config", Version: istioAPIVersion, MessageName: "istio.routing.v1alpha1.DestinationPolicy", Validate: ValidateDestinationPolicy, } // DestinationRule describes destination rules DestinationRule = ProtoSchema{ Type: "destination-rule", Plural: "destination-rules", Group: "networking", Version: "v1alpha3", MessageName: "istio.networking.v1alpha3.DestinationRule", Validate: ValidateDestinationRule, } // HTTPAPISpec describes an HTTP API specification. HTTPAPISpec = ProtoSchema{ Type: "http-api-spec", Plural: "http-api-specs", Group: "config", Version: istioAPIVersion, MessageName: "istio.mixer.v1.config.client.HTTPAPISpec", Validate: ValidateHTTPAPISpec, } // HTTPAPISpecBinding describes an HTTP API specification binding. HTTPAPISpecBinding = ProtoSchema{ Type: "http-api-spec-binding", Plural: "http-api-spec-bindings", Group: "config", Version: istioAPIVersion, MessageName: "istio.mixer.v1.config.client.HTTPAPISpecBinding", Validate: ValidateHTTPAPISpecBinding, } // QuotaSpec describes an Quota specification. QuotaSpec = ProtoSchema{ Type: "quota-spec", Plural: "quota-specs", Group: "config", Version: istioAPIVersion, MessageName: "istio.mixer.v1.config.client.QuotaSpec", Validate: ValidateQuotaSpec, } // QuotaSpecBinding describes an Quota specification binding. QuotaSpecBinding = ProtoSchema{ Type: "quota-spec-binding", Plural: "quota-spec-bindings", Group: "config", Version: istioAPIVersion, MessageName: "istio.mixer.v1.config.client.QuotaSpecBinding", Validate: ValidateQuotaSpecBinding, } // AuthenticationPolicy describes an authentication policy. AuthenticationPolicy = ProtoSchema{ Type: "policy", Plural: "policies", Group: "authentication", Version: "v1alpha1", MessageName: "istio.authentication.v1alpha1.Policy", Validate: ValidateAuthenticationPolicy, } // ServiceRole describes an RBAC service role. ServiceRole = ProtoSchema{ Type: "service-role", Plural: "service-roles", Group: "config", Version: istioAPIVersion, MessageName: "istio.rbac.v1alpha1.ServiceRole", Validate: ValidateServiceRole, } // ServiceRoleBinding describes an RBAC service role. ServiceRoleBinding = ProtoSchema{ Type: "service-role-binding", Plural: "service-role-bindings", Group: "config", Version: istioAPIVersion, MessageName: "istio.rbac.v1alpha1.ServiceRoleBinding", Validate: ValidateServiceRoleBinding, } // IstioConfigTypes lists all Istio config types with schemas and validation IstioConfigTypes = ConfigDescriptor{ RouteRule, VirtualService, IngressRule, Gateway, EgressRule, ServiceEntry, DestinationPolicy, DestinationRule, HTTPAPISpec, HTTPAPISpecBinding, QuotaSpec, QuotaSpecBinding, AuthenticationPolicy, ServiceRole, ServiceRoleBinding, } ) // ResolveHostname uses metadata information to resolve a service reference to // a fully qualified hostname. The metadata namespace and domain are used as // fallback values to fill up the complete name. func ResolveHostname(meta ConfigMeta, svc *routing.IstioService) Hostname { out := svc.Name // if FQDN is specified, do not append domain or namespace to hostname // Service field has precedence over Name if svc.Service != "" { out = svc.Service } else { if svc.Namespace != "" { out = out + "." + svc.Namespace } else if meta.Namespace != "" { out = out + "." + meta.Namespace } if svc.Domain != "" { out = out + "." + svc.Domain } else if meta.Domain != "" { out = out + ".svc." + meta.Domain } } return Hostname(out) } // ResolveShortnameToFQDN uses metadata information to resolve a reference // to shortname of the service to FQDN func ResolveShortnameToFQDN(host string, meta ConfigMeta) Hostname { out := host // Treat the wildcard host as fully qualified. Any other variant of a wildcard hostname will contain a `.` too, // and skip the next if, so we only need to check for the literal wildcard itself. if host == "*" { return Hostname(out) } // if FQDN is specified, do not append domain or namespace to hostname if !strings.Contains(host, ".") { if meta.Namespace != "" { out = out + "." + meta.Namespace } // FIXME this is a gross hack to hardcode a service's domain name in kubernetes // BUG this will break non kubernetes environments if they use shortnames in the // rules. if meta.Domain != "" { out = out + ".svc." + meta.Domain } } return Hostname(out) } // MostSpecificHostMatch compares the elements of the stack to the needle, and returns the longest stack element // matching the needle, or false if no element in the stack matches the needle. func MostSpecificHostMatch(needle Hostname, stack []Hostname) (Hostname, bool) { sort.Sort(Hostnames(stack)) for _, h := range stack { if needle.Matches(h) { return h, true } } return "", false } // istioConfigStore provides a simple adapter for Istio configuration types // from the generic config registry type istioConfigStore struct { ConfigStore } // MakeIstioStore creates a wrapper around a store func MakeIstioStore(store ConfigStore) IstioConfigStore { return &istioConfigStore{store} } // MatchSource checks that a rule applies for source service instances. // Empty source match condition applies for all cases. func
(meta ConfigMeta, source *routing.IstioService, instances []*ServiceInstance) bool { if source == nil { return true } sourceService := ResolveHostname(meta, source) for _, instance := range instances { // must match the source field if it is set if sourceService != instance.Service.Hostname { continue } // must match the labels field - the rule labels are a subset of the instance labels if Labels(source.Labels).SubsetOf(instance.Labels) { return true } } return false } // SortRouteRules sorts a slice of v1alpha1 rules by precedence in a stable manner. func SortRouteRules(rules []Config) { // sort by high precedence first, key string second (keys are unique) sort.Slice(rules, func(i, j int) bool { // protect against incompatible types irule, _ := rules[i].Spec.(*routing.RouteRule) jrule, _ := rules[j].Spec.(*routing.RouteRule) return irule == nil || jrule == nil || irule.Precedence > jrule.Precedence || (irule.Precedence == jrule.Precedence && rules[i].Key() < rules[j].Key()) }) } func (store *istioConfigStore) RouteRules(instances []*ServiceInstance, destination string) []Config { out := make([]Config, 0) configs, err := store.List(RouteRule.Type, NamespaceAll) if err != nil { return nil } for _, config := range configs { rule := config.Spec.(*routing.RouteRule) // validate that rule match predicate applies to destination service hostname := ResolveHostname(config.ConfigMeta, rule.Destination).String() if hostname != destination { continue } // validate that rule match predicate applies to source service instances if rule.Match != nil && !MatchSource(config.ConfigMeta, rule.Match.Source, instances) { continue } out = append(out, config) } return out } func (store *istioConfigStore) RouteRulesByDestination(instances []*ServiceInstance) []Config { out := make([]Config, 0) configs, err := store.List(RouteRule.Type, NamespaceAll) if err != nil { return nil } for _, config := range configs { rule := config.Spec.(*routing.RouteRule) destination := ResolveHostname(config.ConfigMeta, rule.Destination) for _, instance := range instances { if destination.Matches(instance.Service.Hostname) { out = append(out, config) break } } } return out } func (store *istioConfigStore) EgressRules() []Config { configs, err := store.List(EgressRule.Type, NamespaceAll) if err != nil { return nil } return configs } func (store *istioConfigStore) ServiceEntries() []Config { configs, err := store.List(ServiceEntry.Type, NamespaceAll) if err != nil { return nil } return configs } // TODO: move the logic to v2, read all VirtualServices once at startup and per // change event and pass them to the config generator. Model calls to List are // extremely expensive - and for larger number of services it doesn't make sense // to just convert again and again, for each listener times endpoints. func (store *istioConfigStore) VirtualServices(gateways map[string]bool) []Config { configs, err := store.List(VirtualService.Type, NamespaceAll) if err != nil { log.Warnf("Could not load VirtualServices. Error:\n %s \n", err) return nil } out := make([]Config, 0) for _, config := range configs { rule := config.Spec.(*networking.VirtualService) if len(rule.Gateways) == 0 { // This rule applies only to IstioMeshGateway if gateways[IstioMeshGateway] { out = append(out, config) } } else { for _, g := range rule.Gateways { // note: Gateway names do _not_ use wildcard matching, so we do not use Hostname.Matches here if gateways[ResolveShortnameToFQDN(g, config.ConfigMeta).String()] { out = append(out, config) break } else if g == IstioMeshGateway && gateways[g] { // "mesh" gateway cannot be expanded into FQDN out = append(out, config) break } } } } // Need to parse each rule and convert the shortname to FQDN for _, r := range out { rule := r.Spec.(*networking.VirtualService) // resolve top level hosts for i, h := range rule.Hosts { rule.Hosts[i] = ResolveShortnameToFQDN(h, r.ConfigMeta).String() } // resolve gateways to bind to for i, g := range rule.Gateways { if g != IstioMeshGateway { rule.Gateways[i] = ResolveShortnameToFQDN(g, r.ConfigMeta).String() } } // resolve host in http route.destination, route.mirror for _, d := range rule.Http { for _, m := range d.Match { for i, g := range m.Gateways { if g != IstioMeshGateway { m.Gateways[i] = ResolveShortnameToFQDN(g, r.ConfigMeta).String() } } } for _, w := range d.Route { w.Destination.Host = ResolveShortnameToFQDN(w.Destination.Host, r.ConfigMeta).String() } if d.Mirror != nil { d.Mirror.Host = ResolveShortnameToFQDN(d.Mirror.Host, r.ConfigMeta).String() } } //resolve host in tcp route.destination for _, d := range rule.Tcp { for _, m := range d.Match { for i, g := range m.Gateways { if g != IstioMeshGateway { m.Gateways[i] = ResolveShortnameToFQDN(g, r.ConfigMeta).String() } } } for _, w := range d.Route { w.Destination.Host = ResolveShortnameToFQDN(w.Destination.Host, r.ConfigMeta).String() } } } return out } func (store *istioConfigStore) Gateways(workloadLabels LabelsCollection) []Config { configs, err := store.List(Gateway.Type, NamespaceAll) if err != nil { return nil } out := make([]Config, 0) for _, config := range configs { gateway := config.Spec.(*networking.Gateway) if gateway.GetSelector() == nil { // no selector. Applies to all workloads asking for the gateway out = append(out, config) } else { gatewaySelector := Labels(gateway.GetSelector()) if workloadLabels.IsSupersetOf(gatewaySelector) { out = append(out, config) } } } return out } func (store *istioConfigStore) Policy(instances []*ServiceInstance, destination string, labels Labels) *Config { configs, err := store.List(DestinationPolicy.Type, NamespaceAll) if err != nil { return nil } // ugly go-ism var out Config var found bool for _, config := range configs { policy := config.Spec.(*routing.DestinationPolicy) if !MatchSource(config.ConfigMeta, policy.Source, instances) { continue } if destination != ResolveHostname(config.ConfigMeta, policy.Destination).String() { continue } // note the exact label match if !labels.Equals(policy.Destination.Labels) { continue } // pick a deterministic policy from the matching configs by picking the smallest key if !found || out.Key() > config.Key() { out = config found = true } } if !found { return nil } return &out } func (store *istioConfigStore) DestinationRule(hostname Hostname) *Config { configs, err := store.List(DestinationRule.Type, NamespaceAll) if err != nil { return nil } hosts := make([]Hostname, len(configs)) byHosts := make(map[Hostname]*Config, len(configs)) for i := range configs { rule := configs[i].Spec.(*networking.DestinationRule) hosts[i] = ResolveShortnameToFQDN(rule.Host, configs[i].ConfigMeta) byHosts[hosts[i]] = &configs[i] } if c, ok := MostSpecificHostMatch(hostname, hosts); ok { return byHosts[c] } return nil } func (store *istioConfigStore) SubsetToLabels(subsetName string, hostname Hostname) LabelsCollection { // empty subset if subsetName == "" { return nil } config := store.DestinationRule(hostname) if config == nil { return nil } rule := config.Spec.(*networking.DestinationRule) for _, subset := range rule.Subsets { if subset.Name == subsetName { return []Labels{subset.Labels} } } return nil } // `istio.mixer.v1.config.client.IstioService` and // `istio.routing.v1alpha1.IstioService` are logically // equivalent. Convert from mixer-to-proxy representation so we can // use ResolveHostname below. func mixerToProxyIstioService(in *mccpb.IstioService) *routing.IstioService { return &routing.IstioService{ Name: in.Name, Namespace: in.Namespace, Domain: in.Domain, Service: in.Service, Labels: in.Labels, } } // HTTPAPISpecByDestination selects Mixerclient HTTP API Specs // associated with destination service instances. func (store *istioConfigStore) HTTPAPISpecByDestination(instance *ServiceInstance) []Config { bindings, err := store.List(HTTPAPISpecBinding.Type, NamespaceAll) if err != nil { return nil } specs, err := store.List(HTTPAPISpec.Type, NamespaceAll) if err != nil { return nil } // Create a set key from a reference's name and namespace. key := func(name, namespace string) string { return name + "/" + namespace } // Build the set of HTTP API spec references bound to the service instance. refs := make(map[string]struct{}) for _, binding := range bindings { b := binding.Spec.(*mccpb.HTTPAPISpecBinding) for _, service := range b.Services { hostname := ResolveHostname(binding.ConfigMeta, mixerToProxyIstioService(service)) if hostname == instance.Service.Hostname { for _, spec := range b.ApiSpecs { refs[key(spec.Name, spec.Namespace)] = struct{}{} } } } } // Append any spec that is in the set of references. var out []Config for _, spec := range specs { if _, ok := refs[key(spec.ConfigMeta.Name, spec.ConfigMeta.Namespace)]; ok { out = append(out, spec) } } return out } // QuotaSpecByDestination selects Mixerclient quota specifications // associated with destination service instances. func (store *istioConfigStore) QuotaSpecByDestination(instance *ServiceInstance) []Config { bindings, err := store.List(QuotaSpecBinding.Type, NamespaceAll) if err != nil { return nil } specs, err := store.List(QuotaSpec.Type, NamespaceAll) if err != nil { return nil } // Create a set key from a reference's name and namespace. key := func(name, namespace string) string { return name + "/" + namespace } // Build the set of quota spec references bound to the service instance. refs := make(map[string]struct{}) for _, binding := range bindings { b := binding.Spec.(*mccpb.QuotaSpecBinding) for _, service := range b.Services { hostname := ResolveHostname(binding.ConfigMeta, mixerToProxyIstioService(service)) if hostname == instance.Service.Hostname { for _, spec := range b.QuotaSpecs { refs[key(spec.Name, spec.Namespace)] = struct{}{} } } } } // Append any spec that is in the set of references. var out []Config for _, spec := range specs { if _, ok := refs[key(spec.ConfigMeta.Name, spec.ConfigMeta.Namespace)]; ok { out = append(out, spec) } } return out } func (store *istioConfigStore) AuthenticationPolicyByDestination(hostname Hostname, port *Port) *Config { // Hostname should be FQDN, so namespace can be extracted by parsing hostname. parts := strings.Split(string(hostname), ".") if len(parts) < 2 { // Bad hostname, return no policy. return nil } namespace := parts[1] // TODO(diemtvu): check for 'global' policy first, when available. // Tracking issue https://github.com/istio/istio/issues/4027 specs, err := store.List(AuthenticationPolicy.Type, namespace) if err != nil { return nil } var out Config currentMatchLevel := 0 for _, spec := range specs { policy := spec.Spec.(*authn.Policy) // Indicate if a policy matched to target destination: // 0 - not match. // 1 - global / cluster scope. // 2 - namespace scope. // 3 - workload (service). matchLevel := 0 if len(policy.Targets) > 0 { for _, dest := range policy.Targets { if hostname != ResolveHostname(spec.ConfigMeta, &routing.IstioService{Name: dest.Name}) { continue } // If destination port is defined, it must match. if len(dest.Ports) > 0 { portMatched := false for _, portSelector := range dest.Ports { if port.Match(portSelector) { portMatched = true break } } if !portMatched { // Port does not match with any of port selector, skip to next target selector. continue } } matchLevel = 3 break } } else { // Match on namespace level. matchLevel = 2 } // Swap output policy that is match in more specific scope. if matchLevel > currentMatchLevel { currentMatchLevel = matchLevel out = spec } } // Zero-currentMatchLevel implies no config matching the destination found. if currentMatchLevel == 0 { return nil } return &out } // SortHTTPAPISpec sorts a slice in a stable manner. func SortHTTPAPISpec(specs []Config) { sort.Slice(specs, func(i, j int) bool { // protect against incompatible types irule, _ := specs[i].Spec.(*mccpb.HTTPAPISpec) jrule, _ := specs[j].Spec.(*mccpb.HTTPAPISpec) return irule == nil || jrule == nil || (specs[i].Key() < specs[j].Key()) }) } // SortQuotaSpec sorts a slice in a stable manner. func SortQuotaSpec(specs []Config) { sort.Slice(specs, func(i, j int) bool { // protect against incompatible types irule, _ := specs[i].Spec.(*mccpb.QuotaSpec) jrule, _ := specs[j].Spec.(*mccpb.QuotaSpec) return irule == nil || jrule == nil || (specs[i].Key() < specs[j].Key()) }) }
MatchSource
config.py
import os from dotenv import load_dotenv load_dotenv() class Config: SECRET_KEY = os.environ.get('SECRET_KEY') SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://fidel:fidel@localhost/blog' UPLOADED_PHOTOS_DEST = 'app/static/photos' QUOTES_URL = 'http://quotes.stormconsultancy.co.uk/random.json' MAIL_SERVER = 'smtp.googlemail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = os.environ.get("MAIL_USERNAME") MAIL_PASSWORD = os.environ.get("MAIL_PASSWORD") class ProdConfig(Config): SQLALCHEMY_DATABASE_URI =os.environ.get('DATABASE_URL') class DevConfig(Config): #SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://fidel:fidel@localhost/blog'
config_options = { 'development':DevConfig, 'production':ProdConfig }
DEBUG = True
span_utils.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use rustc::session::Session; use save::generated_code; use std::cell::Cell; use syntax::ast; use syntax::codemap::*; use syntax::parse::lexer; use syntax::parse::lexer::{Reader,StringReader}; use syntax::parse::token; use syntax::parse::token::{keywords, Token}; pub struct SpanUtils<'a> { pub sess: &'a Session, pub err_count: Cell<int>, } impl<'a> SpanUtils<'a> { // Standard string for extents/location. pub fn extent_str(&self, span: Span) -> String { let lo_loc = self.sess.codemap().lookup_char_pos(span.lo); let hi_loc = self.sess.codemap().lookup_char_pos(span.hi); let lo_pos = self.sess.codemap().bytepos_to_file_charpos(span.lo); let hi_pos = self.sess.codemap().bytepos_to_file_charpos(span.hi); let lo_pos_byte = self.sess.codemap().lookup_byte_offset(span.lo).pos; let hi_pos_byte = self.sess.codemap().lookup_byte_offset(span.hi).pos; format!("file_name,{},file_line,{},file_col,{},extent_start,{},extent_start_bytes,{},\ file_line_end,{},file_col_end,{},extent_end,{},extent_end_bytes,{}", lo_loc.file.name, lo_loc.line, lo_loc.col.to_uint(), lo_pos.to_uint(), lo_pos_byte.to_uint(), hi_loc.line, hi_loc.col.to_uint(), hi_pos.to_uint(), hi_pos_byte.to_uint()) } // sub_span starts at span.lo, so we need to adjust the positions etc. // If sub_span is None, we don't need to adjust. pub fn make_sub_span(&self, span: Span, sub_span: Option<Span>) -> Option<Span> { let loc = self.sess.codemap().lookup_char_pos(span.lo); assert!(!generated_code(span), "generated code; we should not be processing this `{}` in {}, line {}", self.snippet(span), loc.file.name, loc.line); match sub_span { None => None, Some(sub) => { let FileMapAndBytePos {fm, pos} = self.sess.codemap().lookup_byte_offset(span.lo); let base = pos + fm.start_pos; Some(Span { lo: base + self.sess.codemap().lookup_byte_offset(sub.lo).pos, hi: base + self.sess.codemap().lookup_byte_offset(sub.hi).pos, expn_id: NO_EXPANSION, }) } } } pub fn snippet(&self, span: Span) -> String { match self.sess.codemap().span_to_snippet(span) { Some(s) => s, None => String::new(), } } pub fn retokenise_span(&self, span: Span) -> StringReader<'a> { // sadness - we don't have spans for sub-expressions nor access to the tokens // so in order to get extents for the function name itself (which dxr expects) // we need to re-tokenise the fn definition // Note: this is a bit awful - it adds the contents of span to the end of // the codemap as a new filemap. This is mostly OK, but means we should // not iterate over the codemap. Also, any spans over the new filemap // are incompatible with spans over other filemaps. let filemap = self.sess.codemap().new_filemap(String::from_str("<anon-dxr>"), self.snippet(span)); let s = self.sess; lexer::StringReader::new(s.diagnostic(), filemap) } // Re-parses a path and returns the span for the last identifier in the path pub fn span_for_last_ident(&self, span: Span) -> Option<Span> { let mut result = None; let mut toks = self.retokenise_span(span); let mut bracket_count = 0u; loop { let ts = toks.real_token(); if ts.tok == token::Eof { return self.make_sub_span(span, result) } if bracket_count == 0 && (ts.tok.is_ident() || ts.tok.is_keyword(keywords::Self)) { result = Some(ts.sp); } bracket_count += match ts.tok { token::Lt => 1, token::Gt => -1, token::BinOp(token::Shr) => -2, _ => 0 } } } // Return the span for the first identifier in the path. pub fn span_for_first_ident(&self, span: Span) -> Option<Span> { let mut toks = self.retokenise_span(span); let mut bracket_count = 0u; loop { let ts = toks.real_token(); if ts.tok == token::Eof { return None; } if bracket_count == 0 && (ts.tok.is_ident() || ts.tok.is_keyword(keywords::Self)) { return self.make_sub_span(span, Some(ts.sp)); } bracket_count += match ts.tok { token::Lt => 1, token::Gt => -1, token::BinOp(token::Shr) => -2, _ => 0 } } } // Return the span for the last ident before a `(` or `<` or '::<' and outside any // any brackets, or the last span. pub fn sub_span_for_meth_name(&self, span: Span) -> Option<Span> { let mut toks = self.retokenise_span(span); let mut prev = toks.real_token(); let mut result = None; let mut bracket_count = 0u; let mut last_span = None; while prev.tok != token::Eof { last_span = None; let mut next = toks.real_token(); if (next.tok == token::OpenDelim(token::Paren) || next.tok == token::Lt) && bracket_count == 0 && prev.tok.is_ident() { result = Some(prev.sp); } if bracket_count == 0 && next.tok == token::ModSep { let old = prev; prev = next; next = toks.real_token(); if next.tok == token::Lt && old.tok.is_ident() { result = Some(old.sp); } } bracket_count += match prev.tok { token::OpenDelim(token::Paren) | token::Lt => 1, token::CloseDelim(token::Paren) | token::Gt => -1, token::BinOp(token::Shr) => -2, _ => 0 }; if prev.tok.is_ident() && bracket_count == 0 { last_span = Some(prev.sp); } prev = next; } if result.is_none() && last_span.is_some() { return self.make_sub_span(span, last_span); } return self.make_sub_span(span, result); } // Return the span for the last ident before a `<` and outside any // brackets, or the last span. pub fn sub_span_for_type_name(&self, span: Span) -> Option<Span> { let mut toks = self.retokenise_span(span); let mut prev = toks.real_token(); let mut result = None; let mut bracket_count = 0u; loop { let next = toks.real_token(); if (next.tok == token::Lt || next.tok == token::Colon) && bracket_count == 0 && prev.tok.is_ident() { result = Some(prev.sp); } bracket_count += match prev.tok { token::Lt => 1, token::Gt => -1, token::BinOp(token::Shr) => -2, _ => 0 }; if next.tok == token::Eof { break; } prev = next; } if bracket_count != 0 { let loc = self.sess.codemap().lookup_char_pos(span.lo); self.sess.span_bug(span, format!("Mis-counted brackets when breaking path? Parsing '{}' in {}, line {}", self.snippet(span), loc.file.name, loc.line).as_slice()); } if result.is_none() && prev.tok.is_ident() && bracket_count == 0 { return self.make_sub_span(span, Some(prev.sp)); } self.make_sub_span(span, result) } // Reparse span and return an owned vector of sub spans of the first limit // identifier tokens in the given nesting level. // example with Foo<Bar<T,V>, Bar<T,V>> // Nesting = 0: all idents outside of brackets: ~[Foo] // Nesting = 1: idents within one level of brackets: ~[Bar, Bar] pub fn spans_with_brackets(&self, span: Span, nesting: int, limit: int) -> Vec<Span> { let mut result: Vec<Span> = vec!(); let mut toks = self.retokenise_span(span); // We keep track of how many brackets we're nested in let mut bracket_count = 0i; loop { let ts = toks.real_token(); if ts.tok == token::Eof { if bracket_count != 0 { let loc = self.sess.codemap().lookup_char_pos(span.lo); self.sess.span_bug(span, format!( "Mis-counted brackets when breaking path? Parsing '{}' in {}, line {}", self.snippet(span), loc.file.name, loc.line).as_slice()); } return result } if (result.len() as int) == limit { return result; } bracket_count += match ts.tok { token::Lt => 1, token::Gt => -1, token::BinOp(token::Shl) => 2, token::BinOp(token::Shr) => -2, _ => 0 }; if ts.tok.is_ident() && bracket_count == nesting { result.push(self.make_sub_span(span, Some(ts.sp)).unwrap()); } } } pub fn sub_span_before_token(&self, span: Span, tok: Token) -> Option<Span> { let mut toks = self.retokenise_span(span); let mut prev = toks.real_token(); loop { if prev.tok == token::Eof { return None; } let next = toks.real_token(); if next.tok == tok { return self.make_sub_span(span, Some(prev.sp)); } prev = next; } } pub fn sub_span_after_keyword(&self, span: Span, keyword: keywords::Keyword) -> Option<Span> { let mut toks = self.retokenise_span(span); loop { let ts = toks.real_token(); if ts.tok == token::Eof { return None; } if ts.tok.is_keyword(keyword) { let ts = toks.real_token(); if ts.tok == token::Eof { return None } else { return self.make_sub_span(span, Some(ts.sp)); } } } } // Returns a list of the spans of idents in a patch. // E.g., For foo::bar<x,t>::baz, we return [foo, bar, baz] (well, their spans) pub fn spans_for_path_segments(&self, path: &ast::Path) -> Vec<Span> { if generated_code(path.span) { return vec!(); } self.spans_with_brackets(path.span, 0, -1) } // Return an owned vector of the subspans of the param identifier // tokens found in span. pub fn spans_for_ty_params(&self, span: Span, number: int) -> Vec<Span> { if generated_code(span) { return vec!(); } // Type params are nested within one level of brackets: // i.e. we want ~[A, B] from Foo<A, B<T,U>> self.spans_with_brackets(span, 1, number) } pub fn report_span_err(&self, kind: &str, span: Span)
}
{ let loc = self.sess.codemap().lookup_char_pos(span.lo); info!("({}) Could not find sub_span in `{}` in {}, line {}", kind, self.snippet(span), loc.file.name, loc.line); self.err_count.set(self.err_count.get()+1); if self.err_count.get() > 1000 { self.sess.bug("span errors reached 1000, giving up"); } }
schema.py
# https://github.com/keleshev/schema # Copyright (c) 2012 Vladimir Keleshev, <[email protected]> # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # yapf: disable # Source code start: updated Aug 18, 2020 import re try: from contextlib import ExitStack except ImportError: from contextlib2 import ExitStack __version__ = "0.7.3" __all__ = [ "Schema", "And", "Or", "Regex", "Optional", "Use", "Forbidden", "Const", "Literal", "SchemaError", "SchemaWrongKeyError", "SchemaMissingKeyError", "SchemaForbiddenKeyError", "SchemaUnexpectedTypeError", "SchemaOnlyOneAllowedError", ] class SchemaError(Exception): """Error during Schema validation.""" def __init__(self, autos, errors=None): self.autos = autos if type(autos) is list else [autos] self.errors = errors if type(errors) is list else [errors] Exception.__init__(self, self.code) @property def code(self): """ Removes duplicates values in auto and error list. parameters. """ def uniq(seq): """ Utility function that removes duplicate. """ seen = set() seen_add = seen.add # This way removes duplicates while preserving the order. return [x for x in seq if x not in seen and not seen_add(x)] data_set = uniq(i for i in self.autos if i is not None) error_list = uniq(i for i in self.errors if i is not None) if error_list: return "\n".join(error_list) return "\n".join(data_set) class SchemaWrongKeyError(SchemaError): """Error Should be raised when an unexpected key is detected within the data set being.""" pass class SchemaMissingKeyError(SchemaError): """Error should be raised when a mandatory key is not found within the data set being validated""" pass class SchemaOnlyOneAllowedError(SchemaError): """Error should be raised when an only_one Or key has multiple matching candidates""" pass class SchemaForbiddenKeyError(SchemaError): """Error should be raised when a forbidden key is found within the data set being validated, and its value matches the value that was specified""" pass class SchemaUnexpectedTypeError(SchemaError): """Error should be raised when a type mismatch is detected within the data set being validated.""" pass class And(object): """ Utility function to combine validation directives in AND Boolean fashion. """ def __init__(self, *args, **kw): self._args = args if not set(kw).issubset({"error", "schema", "ignore_extra_keys"}): diff = {"error", "schema", "ignore_extra_keys"}.difference(kw) raise TypeError("Unknown keyword arguments %r" % list(diff)) self._error = kw.get("error") self._ignore_extra_keys = kw.get("ignore_extra_keys", False) # You can pass your inherited Schema class. self._schema = kw.get("schema", Schema) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, ", ".join(repr(a) for a in self._args)) @property def args(self): """The provided parameters""" return self._args def validate(self, data): """ Validate data using defined sub schema/expressions ensuring all values are valid. :param data: to be validated with sub defined schemas. :return: returns validated data """ for s in [self._schema(s, error=self._error, ignore_extra_keys=self._ignore_extra_keys) for s in self._args]: data = s.validate(data) return data class Or(And): """Utility function to combine validation directives in a OR Boolean fashion.""" def __init__(self, *args, **kwargs): self.only_one = kwargs.pop("only_one", False) self.match_count = 0 super(Or, self).__init__(*args, **kwargs) def reset(self): failed = self.match_count > 1 and self.only_one self.match_count = 0 if failed: raise SchemaOnlyOneAllowedError(["There are multiple keys present " + "from the %r condition" % self]) def validate(self, data): """ Validate data using sub defined schema/expressions ensuring at least one value is valid. :param data: data to be validated by provided schema. :return: return validated data if not validation """ autos, errors = [], [] for s in [self._schema(s, error=self._error, ignore_extra_keys=self._ignore_extra_keys) for s in self._args]: try: validation = s.validate(data) self.match_count += 1 if self.match_count > 1 and self.only_one: break return validation except SchemaError as _x: autos += _x.autos errors += _x.errors raise SchemaError( ["%r did not validate %r" % (self, data)] + autos, [self._error.format(data) if self._error else None] + errors, ) class Regex(object): """ Enables schema.py to validate string using regular expressions. """ # Map all flags bits to a more readable description NAMES = [ "re.ASCII", "re.DEBUG", "re.VERBOSE", "re.UNICODE", "re.DOTALL", "re.MULTILINE", "re.LOCALE", "re.IGNORECASE", "re.TEMPLATE", ] def __init__(self, pattern_str, flags=0, error=None): self._pattern_str = pattern_str flags_list = [Regex.NAMES[i] for i, f in enumerate("{0:09b}".format(flags)) if f != "0"] # Name for each bit if flags_list: self._flags_names = ", flags=" + "|".join(flags_list) else: self._flags_names = "" self._pattern = re.compile(pattern_str, flags=flags) self._error = error def __repr__(self): return "%s(%r%s)" % (self.__class__.__name__, self._pattern_str, self._flags_names) @property def
(self): """The pattern for the represented regular expression""" return self._pattern_str def validate(self, data): """ Validated data using defined regex. :param data: data to be validated :return: return validated data. """ e = self._error try: if self._pattern.search(data): return data else: raise SchemaError("%r does not match %r" % (self, data), e) except TypeError: raise SchemaError("%r is not string nor buffer" % data, e) class Use(object): """ For more general use cases, you can use the Use class to transform the data while it is being validate. """ def __init__(self, callable_, error=None): if not callable(callable_): raise TypeError("Expected a callable, not %r" % callable_) self._callable = callable_ self._error = error def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self._callable) def validate(self, data): try: return self._callable(data) except SchemaError as x: raise SchemaError([None] + x.autos, [self._error.format(data) if self._error else None] + x.errors) except BaseException as x: f = _callable_str(self._callable) raise SchemaError("%s(%r) raised %r" % (f, data, x), self._error.format(data) if self._error else None) COMPARABLE, CALLABLE, VALIDATOR, TYPE, DICT, ITERABLE = range(6) def _priority(s): """Return priority for a given object.""" if type(s) in (list, tuple, set, frozenset): return ITERABLE if type(s) is dict: return DICT if issubclass(type(s), type): return TYPE if isinstance(s, Literal): return COMPARABLE if hasattr(s, "validate"): return VALIDATOR if callable(s): return CALLABLE else: return COMPARABLE class Schema(object): """ Entry point of the library, use this class to instantiate validation schema for the data that will be validated. """ def __init__(self, schema, error=None, ignore_extra_keys=False, name=None, description=None, as_reference=False): self._schema = schema self._error = error self._ignore_extra_keys = ignore_extra_keys self._name = name self._description = description # Ask json_schema to create a definition for this schema and use it as part of another self.as_reference = as_reference if as_reference and name is None: raise ValueError("Schema used as reference should have a name") def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self._schema) @property def schema(self): return self._schema @property def description(self): return self._description @property def name(self): return self._name @property def ignore_extra_keys(self): return self._ignore_extra_keys @staticmethod def _dict_key_priority(s): """Return priority for a given key object.""" if isinstance(s, Hook): return _priority(s._schema) - 0.5 if isinstance(s, Optional): return _priority(s._schema) + 0.5 return _priority(s) @staticmethod def _is_optional_type(s): """Return True if the given key is optional (does not have to be found)""" return any(isinstance(s, optional_type) for optional_type in [Optional, Hook]) def is_valid(self, data): """Return whether the given data has passed all the validations that were specified in the given schema. """ try: self.validate(data) except SchemaError: return False else: return True def _prepend_schema_name(self, message): """ If a custom schema name has been defined, prepends it to the error message that gets raised when a schema error occurs. """ if self._name: message = "{0!r} {1!s}".format(self._name, message) return message def validate(self, data): Schema = self.__class__ s = self._schema e = self._error.format(data) if self._error else None i = self._ignore_extra_keys if isinstance(s, Literal): s = s.schema flavor = _priority(s) if flavor == ITERABLE: data = Schema(type(s), error=e).validate(data) o = Or(*s, error=e, schema=Schema, ignore_extra_keys=i) return type(data)(o.validate(d) for d in data) if flavor == DICT: exitstack = ExitStack() data = Schema(dict, error=e).validate(data) new = type(data)() # new - is a dict of the validated values coverage = set() # matched schema keys # for each key and value find a schema entry matching them, if any sorted_skeys = sorted(s, key=self._dict_key_priority) for skey in sorted_skeys: if hasattr(skey, "reset"): exitstack.callback(skey.reset) with exitstack: # Evaluate dictionaries last data_items = sorted(data.items(), key=lambda value: isinstance(value[1], dict)) for key, value in data_items: for skey in sorted_skeys: svalue = s[skey] try: nkey = Schema(skey, error=e).validate(key) except SchemaError: pass else: if isinstance(skey, Hook): # As the content of the value makes little sense for # keys with a hook, we reverse its meaning: # we will only call the handler if the value does match # In the case of the forbidden key hook, # we will raise the SchemaErrorForbiddenKey exception # on match, allowing for excluding a key only if its # value has a certain type, and allowing Forbidden to # work well in combination with Optional. try: nvalue = Schema(svalue, error=e).validate(value) except SchemaError: continue skey.handler(nkey, data, e) else: try: nvalue = Schema(svalue, error=e, ignore_extra_keys=i).validate(value) except SchemaError as x: k = "Key '%s' error:" % nkey message = self._prepend_schema_name(k) raise SchemaError([message] + x.autos, [e] + x.errors) else: new[nkey] = nvalue coverage.add(skey) break required = set(k for k in s if not self._is_optional_type(k)) if not required.issubset(coverage): missing_keys = required - coverage s_missing_keys = ", ".join(repr(k) for k in sorted(missing_keys, key=repr)) message = "Missing key%s: %s" % (_plural_s(missing_keys), s_missing_keys) message = self._prepend_schema_name(message) raise SchemaMissingKeyError(message, e) if not self._ignore_extra_keys and (len(new) != len(data)): wrong_keys = set(data.keys()) - set(new.keys()) s_wrong_keys = ", ".join(repr(k) for k in sorted(wrong_keys, key=repr)) message = "Wrong key%s %s in %r" % (_plural_s(wrong_keys), s_wrong_keys, data) message = self._prepend_schema_name(message) raise SchemaWrongKeyError(message, e) # Apply default-having optionals that haven't been used: defaults = set(k for k in s if type(k) is Optional and hasattr(k, "default")) - coverage for default in defaults: new[default.key] = default.default() if callable(default.default) else default.default return new if flavor == TYPE: if isinstance(data, s) and not (isinstance(data, bool) and s == int): return data else: message = "%r should be instance of %r" % (data, s.__name__) message = self._prepend_schema_name(message) raise SchemaUnexpectedTypeError(message, e) if flavor == VALIDATOR: try: return s.validate(data) except SchemaError as x: raise SchemaError([None] + x.autos, [e] + x.errors) except BaseException as x: message = "%r.validate(%r) raised %r" % (s, data, x) message = self._prepend_schema_name(message) raise SchemaError(message, e) if flavor == CALLABLE: f = _callable_str(s) try: if s(data): return data except SchemaError as x: raise SchemaError([None] + x.autos, [e] + x.errors) except BaseException as x: message = "%s(%r) raised %r" % (f, data, x) message = self._prepend_schema_name(message) raise SchemaError(message, e) message = "%s(%r) should evaluate to True" % (f, data) message = self._prepend_schema_name(message) raise SchemaError(message, e) if s == data: return data else: message = "%r does not match %r" % (s, data) message = self._prepend_schema_name(message) raise SchemaError(message, e) def json_schema(self, schema_id, use_refs=False): """Generate a draft-07 JSON schema dict representing the Schema. This method can only be called when the Schema's value is a dict. This method must be called with a schema_id. :param schema_id: The value of the $id on the main schema :param use_refs: Enable reusing object references in the resulting JSON schema. Schemas with references are harder to read by humans, but are a lot smaller when there is a lot of reuse """ seen = dict() # For use_refs definitions_by_name = {} def _json_schema(schema, is_main_schema=True, description=None, allow_reference=True): Schema = self.__class__ def _create_or_use_ref(return_dict): """If not already seen, return the provided part of the schema unchanged. If already seen, give an id to the already seen dict and return a reference to the previous part of the schema instead. """ if not use_refs or is_main_schema: return return_schema hashed = hash(repr(sorted(return_dict.items()))) if hashed not in seen: seen[hashed] = return_dict return return_dict else: id_str = "#" + str(hashed) seen[hashed]["$id"] = id_str return {"$ref": id_str} def _get_type_name(python_type): """Return the JSON schema name for a Python type""" if python_type == str: return "string" elif python_type == int: return "integer" elif python_type == float: return "number" elif python_type == bool: return "boolean" elif python_type == list: return "array" elif python_type == dict: return "object" return "string" def _to_json_type(value): """Attempt to convert a constant value (for "const" and "default") to a JSON serializable value""" if value is None or type(value) in (str, int, float, bool, list, dict): return value if type(value) in (tuple, set, frozenset): return list(value) if isinstance(value, Literal): return value.schema return str(value) def _to_schema(s, ignore_extra_keys): if not isinstance(s, Schema): return Schema(s, ignore_extra_keys=ignore_extra_keys) return s s = schema.schema i = schema.ignore_extra_keys flavor = _priority(s) return_schema = {} is_a_ref = allow_reference and schema.as_reference return_description = description or schema.description if return_description: return_schema["description"] = return_description if flavor == TYPE: # Handle type return_schema["type"] = _get_type_name(s) elif flavor == ITERABLE: # Handle arrays or dict schema return_schema["type"] = "array" if len(s) == 1: return_schema["items"] = _json_schema(_to_schema(s[0], i), is_main_schema=False) elif len(s) > 1: return_schema["items"] = _json_schema(Schema(Or(*s)), is_main_schema=False) elif isinstance(s, Or): # Handle Or values # Check if we can use an enum if all(priority == COMPARABLE for priority in [_priority(value) for value in s.args]): or_values = [str(s) if isinstance(s, Literal) else s for s in s.args] # All values are simple, can use enum or const if len(or_values) == 1: return_schema["const"] = _to_json_type(or_values[0]) return return_schema return_schema["enum"] = or_values else: # No enum, let's go with recursive calls any_of_values = [] for or_key in s.args: new_value = _json_schema(_to_schema(or_key, i), is_main_schema=False) if new_value != {} and new_value not in any_of_values: any_of_values.append(new_value) if len(any_of_values) == 1: # Only one representable condition remains, do not put under oneOf return_schema.update(any_of_values[0]) else: return_schema["anyOf"] = any_of_values elif isinstance(s, And): # Handle And values all_of_values = [] for and_key in s.args: new_value = _json_schema(_to_schema(and_key, i), is_main_schema=False) if new_value != {} and new_value not in all_of_values: all_of_values.append(new_value) if len(all_of_values) == 1: # Only one representable condition remains, do not put under allOf return_schema.update(all_of_values[0]) else: return_schema["allOf"] = all_of_values elif flavor == COMPARABLE: return_schema["const"] = _to_json_type(s) elif flavor == VALIDATOR and type(s) == Regex: return_schema["type"] = "string" return_schema["pattern"] = s.pattern_str else: if flavor != DICT: # If not handled, do not check return return_schema # Schema is a dict # Check if we have to create a common definition and use as reference if is_a_ref: # Generate sub schema if not already done if schema.name not in definitions_by_name: definitions_by_name[schema.name] = {} # Avoid infinite loop definitions_by_name[schema.name] = _json_schema( schema, is_main_schema=False, allow_reference=False ) return_schema["$ref"] = "#/definitions/" + schema.name else: required_keys = [] expanded_schema = {} for key in s: if isinstance(key, Hook): continue def _get_key_description(key): """Get the description associated to a key (as specified in a Literal object). Return None if not a Literal""" if isinstance(key, Optional): return _get_key_description(key.schema) if isinstance(key, Literal): return key.description return None def _get_key_name(key): """Get the name of a key (as specified in a Literal object). Return the key unchanged if not a Literal""" if isinstance(key, Optional): return _get_key_name(key.schema) if isinstance(key, Literal): return key.schema return key sub_schema = _to_schema(s[key], ignore_extra_keys=i) key_name = _get_key_name(key) if isinstance(key_name, str): if not isinstance(key, Optional): required_keys.append(key_name) expanded_schema[key_name] = _json_schema( sub_schema, is_main_schema=False, description=_get_key_description(key) ) if isinstance(key, Optional) and hasattr(key, "default"): expanded_schema[key_name]["default"] = _to_json_type(key.default) elif isinstance(key_name, Or): # JSON schema does not support having a key named one name or another, so we just add both options # This is less strict because we cannot enforce that one or the other is required for or_key in key_name.args: expanded_schema[_get_key_name(or_key)] = _json_schema( sub_schema, is_main_schema=False, description=_get_key_description(or_key) ) return_schema.update( { "type": "object", "properties": expanded_schema, "required": required_keys, "additionalProperties": i, } ) if is_main_schema: return_schema.update({"$id": schema_id, "$schema": "http://json-schema.org/draft-07/schema#"}) if self._name: return_schema["title"] = self._name if definitions_by_name: return_schema["definitions"] = {} for definition_name, definition in definitions_by_name.items(): return_schema["definitions"][definition_name] = definition return _create_or_use_ref(return_schema) return _json_schema(self, True) class Optional(Schema): """Marker for an optional part of the validation Schema.""" _MARKER = object() def __init__(self, *args, **kwargs): default = kwargs.pop("default", self._MARKER) super(Optional, self).__init__(*args, **kwargs) if default is not self._MARKER: # See if I can come up with a static key to use for myself: if _priority(self._schema) != COMPARABLE: raise TypeError( "Optional keys with defaults must have simple, " "predictable values, like literal strings or ints. " '"%r" is too complex.' % (self._schema,) ) self.default = default self.key = str(self._schema) def __hash__(self): return hash(self._schema) def __eq__(self, other): return ( self.__class__ is other.__class__ and getattr(self, "default", self._MARKER) == getattr(other, "default", self._MARKER) and self._schema == other._schema ) def reset(self): if hasattr(self._schema, "reset"): self._schema.reset() class Hook(Schema): def __init__(self, *args, **kwargs): self.handler = kwargs.pop("handler", lambda *args: None) super(Hook, self).__init__(*args, **kwargs) self.key = self._schema class Forbidden(Hook): def __init__(self, *args, **kwargs): kwargs["handler"] = self._default_function super(Forbidden, self).__init__(*args, **kwargs) @staticmethod def _default_function(nkey, data, error): raise SchemaForbiddenKeyError("Forbidden key encountered: %r in %r" % (nkey, data), error) class Literal(object): def __init__(self, value, description=None): self._schema = value self._description = description def __str__(self): return self._schema def __repr__(self): return 'Literal("' + self.schema + '", description="' + (self.description or "") + '")' @property def description(self): return self._description @property def schema(self): return self._schema class Const(Schema): def validate(self, data): super(Const, self).validate(data) return data def _callable_str(callable_): if hasattr(callable_, "__name__"): return callable_.__name__ return str(callable_) def _plural_s(sized): return "s" if len(sized) > 1 else ""
pattern_str
ExpandableElement.tsx
import { Collapse, ListItem } from '@material-ui/core' import { createStyles, makeStyles, Theme } from '@material-ui/core/styles' import { ExpandLess, ExpandMore } from '@material-ui/icons' import { ReactElement, ReactNode, useState } from 'react' const useStyles = makeStyles((theme: Theme) => createStyles({ root: { width: '100%', padding: 0, margin: 0, marginTop: theme.spacing(4), '&:first-child': { marginTop: 0, }, }, rootLevel1: { marginTop: theme.spacing(1) }, rootLevel2: { marginTop: theme.spacing(0.5) }, header: { backgroundColor: theme.palette.background.paper, }, contentLevel0: { marginTop: theme.spacing(1), }, contentLevel12: { marginTop: theme.spacing(0.25), }, infoText: { color: '#c9c9c9', }, }), ) interface Props { children: ReactNode expandable: ReactNode defaultOpen?: boolean } export default function ExpandableElement({ children, expandable, defaultOpen }: Props): ReactElement | null { const classes = useStyles() const [open, setOpen] = useState<boolean>(Boolean(defaultOpen)) const handleClick = () => { setOpen(!open) } return ( <div className={`${classes.root} ${classes.rootLevel2}`}> <ListItem button onClick={handleClick} className={classes.header}> {children} {open ? <ExpandLess /> : <ExpandMore />} </ListItem> <Collapse in={open} timeout="auto" unmountOnExit> <div className={classes.contentLevel12}>{expandable}</div>
}
</Collapse> </div> )
seed.rs
// Copyright 2020 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Seeds a server with initial peers on first start and keep monitoring //! peer counts to connect to more if neeed. Seedin strategy is //! configurable with either no peers, a user-defined list or a preset //! list of DNS records (the default). use chrono::prelude::{DateTime, Utc}; use chrono::{Duration, MIN_DATE}; use rand::seq::SliceRandom; use rand::thread_rng; use std::collections::HashMap; use std::net::ToSocketAddrs; use std::sync::{mpsc, Arc}; use std::{cmp, str, thread, time}; use crate::core::global; use crate::p2p; use crate::p2p::types::PeerAddr; use crate::p2p::ChainAdapter; use crate::util::StopState; // DNS Seeds with contact email associated const MAINNET_DNS_SEEDS: &'static [&'static str] = &[ "mainnet.seed.grin.icu", // [email protected] "mainnet.seed.713.mw", // [email protected] "mainnet.seed.grin.lesceller.com", // [email protected] "mainnet.seed.grin.prokapi.com", // [email protected] "grinseed.yeastplume.org", // [email protected] ]; const FLOONET_DNS_SEEDS: &'static [&'static str] = &[ "floonet.seed.grin.icu", // [email protected] "floonet.seed.713.mw", // [email protected] "floonet.seed.grin.lesceller.com", // [email protected] "floonet.seed.grin.prokapi.com", // [email protected] ]; pub fn connect_and_monitor( p2p_server: Arc<p2p::Server>, capabilities: p2p::Capabilities, seed_list: Box<dyn Fn() -> Vec<PeerAddr> + Send>, preferred_peers: Option<Vec<PeerAddr>>, stop_state: Arc<StopState>, ) -> std::io::Result<thread::JoinHandle<()>> { thread::Builder::new() .name("seed".to_string()) .spawn(move || { let peers = p2p_server.peers.clone(); // open a channel with a listener that connects every peer address sent below // max peer count let (tx, rx) = mpsc::channel(); // check seeds first connect_to_seeds_and_preferred_peers( peers.clone(), tx.clone(), seed_list, preferred_peers.clone(), ); let mut prev = MIN_DATE.and_hms(0, 0, 0); let mut prev_expire_check = MIN_DATE.and_hms(0, 0, 0); let mut prev_ping = Utc::now(); let mut start_attempt = 0; let mut connecting_history: HashMap<PeerAddr, DateTime<Utc>> = HashMap::new(); loop { if stop_state.is_stopped() { break; } // Pause egress peer connection request. Only for tests. if stop_state.is_paused() { thread::sleep(time::Duration::from_secs(1)); continue; } // Check for and remove expired peers from the storage if Utc::now() - prev_expire_check > Duration::hours(1) { peers.remove_expired(); prev_expire_check = Utc::now(); } // make several attempts to get peers as quick as possible // with exponential backoff if Utc::now() - prev > Duration::seconds(cmp::min(20, 1 << start_attempt)) { // try to connect to any address sent to the channel listen_for_addrs( peers.clone(), p2p_server.clone(), capabilities, &rx, &mut connecting_history, ); // monitor additional peers if we need to add more monitor_peers( peers.clone(), p2p_server.config.clone(), tx.clone(), preferred_peers.clone(), ); prev = Utc::now(); start_attempt = cmp::min(6, start_attempt + 1); } // Ping connected peers on every 10s to monitor peers. if Utc::now() - prev_ping > Duration::seconds(10) { let total_diff = peers.total_difficulty(); let total_height = peers.total_height(); if total_diff.is_ok() && total_height.is_ok() { peers.check_all(total_diff.unwrap(), total_height.unwrap()); prev_ping = Utc::now(); } else { error!("failed to get peers difficulty and/or height"); } } thread::sleep(time::Duration::from_secs(1)); } }) } fn monitor_peers( peers: Arc<p2p::Peers>, config: p2p::P2PConfig, tx: mpsc::Sender<PeerAddr>, preferred_peers_list: Option<Vec<PeerAddr>>, ) { // regularly check if we need to acquire more peers and if so, gets // them from db let total_count = peers.all_peers().len(); let mut healthy_count = 0; let mut banned_count = 0; let mut defuncts = vec![]; for x in peers.all_peers() { match x.flags { p2p::State::Banned => { let interval = Utc::now().timestamp() - x.last_banned; // Unban peer if interval >= config.ban_window() { if let Err(e) = peers.unban_peer(x.addr) { error!("failed to unban peer {}: {:?}", x.addr, e); } debug!( "monitor_peers: unbanned {} after {} seconds", x.addr, interval ); } else { banned_count += 1; } } p2p::State::Healthy => healthy_count += 1, p2p::State::Defunct => defuncts.push(x), } } debug!( "monitor_peers: on {}:{}, {} connected ({} most_work). \ all {} = {} healthy + {} banned + {} defunct", config.host, config.port, peers.peer_count(), peers.most_work_peers().len(), total_count, healthy_count, banned_count, defuncts.len(), ); // maintenance step first, clean up p2p server peers peers.clean_peers( config.peer_max_inbound_count() as usize, config.peer_max_outbound_count() as usize, ); if peers.enough_outbound_peers() { return; } // loop over connected peers // ask them for their list of peers let mut connected_peers: Vec<PeerAddr> = vec![]; for p in peers.connected_peers() { trace!( "monitor_peers: {}:{} ask {} for more peers", config.host, config.port, p.info.addr, ); let _ = p.send_peer_request(p2p::Capabilities::PEER_LIST); connected_peers.push(p.info.addr) } // Attempt to connect to preferred peers if there is some if let Some(preferred_peers) = preferred_peers_list { for p in preferred_peers { if !connected_peers.is_empty() { if !connected_peers.contains(&p) { tx.send(p).unwrap(); } } else { tx.send(p).unwrap(); } } } // take a random defunct peer and mark it healthy: over a long period any // peer will see another as defunct eventually, gives us a chance to retry if defuncts.len() > 0 { defuncts.shuffle(&mut thread_rng()); let _ = peers.update_state(defuncts[0].addr, p2p::State::Healthy); } // find some peers from our db // and queue them up for a connection attempt // intentionally make too many attempts (2x) as some (most?) will fail // as many nodes in our db are not publicly accessible let max_peer_attempts = 128; let new_peers = peers.find_peers( p2p::State::Healthy, p2p::Capabilities::UNKNOWN, max_peer_attempts as usize, ); // Only queue up connection attempts for candidate peers where we // are confident we do not yet know about this peer. // The call to is_known() may fail due to contention on the peers map.
tx.send(p.addr).unwrap(); } } } // Check if we have any pre-existing peer in db. If so, start with those, // otherwise use the seeds provided. fn connect_to_seeds_and_preferred_peers( peers: Arc<p2p::Peers>, tx: mpsc::Sender<PeerAddr>, seed_list: Box<dyn Fn() -> Vec<PeerAddr>>, peers_preferred_list: Option<Vec<PeerAddr>>, ) { // check if we have some peers in db // look for peers that are able to give us other peers (via PEER_LIST capability) let peers = peers.find_peers(p2p::State::Healthy, p2p::Capabilities::PEER_LIST, 100); // if so, get their addresses, otherwise use our seeds let mut peer_addrs = if peers.len() > 3 { peers.iter().map(|p| p.addr).collect::<Vec<_>>() } else { seed_list() }; // If we have preferred peers add them to the connection match peers_preferred_list { Some(mut peers_preferred) => peer_addrs.append(&mut peers_preferred), None => trace!("No preferred peers"), }; if peer_addrs.len() == 0 { warn!("No seeds were retrieved."); } // connect to this first set of addresses for addr in peer_addrs { tx.send(addr).unwrap(); } } /// Regularly poll a channel receiver for new addresses and initiate a /// connection if the max peer count isn't exceeded. A request for more /// peers is also automatically sent after connection. fn listen_for_addrs( peers: Arc<p2p::Peers>, p2p: Arc<p2p::Server>, capab: p2p::Capabilities, rx: &mpsc::Receiver<PeerAddr>, connecting_history: &mut HashMap<PeerAddr, DateTime<Utc>>, ) { // Pull everything currently on the queue off the queue. // Does not block so addrs may be empty. // We will take(max_peers) from this later but we want to drain the rx queue // here to prevent it backing up. let addrs: Vec<PeerAddr> = rx.try_iter().collect(); // If we have a healthy number of outbound peers then we are done here. if peers.enough_outbound_peers() { return; } // Note: We drained the rx queue earlier to keep it under control. // Even if there are many addresses to try we will only try a bounded number of them for safety. let connect_min_interval = 30; let max_outbound_attempts = 128; for addr in addrs.into_iter().take(max_outbound_attempts) { // ignore the duplicate connecting to same peer within 30 seconds let now = Utc::now(); if let Some(last_connect_time) = connecting_history.get(&addr) { if *last_connect_time + Duration::seconds(connect_min_interval) > now { debug!( "peer_connect: ignore a duplicate request to {}. previous connecting time: {}", addr, last_connect_time.format("%H:%M:%S%.3f").to_string(), ); continue; } else { if let Some(history) = connecting_history.get_mut(&addr) { *history = now; } } } connecting_history.insert(addr, now); let peers_c = peers.clone(); let p2p_c = p2p.clone(); thread::Builder::new() .name("peer_connect".to_string()) .spawn(move || match p2p_c.connect(addr) { Ok(p) => { if p.send_peer_request(capab).is_ok() { let _ = peers_c.update_state(addr, p2p::State::Healthy); } } Err(_) => { let _ = peers_c.update_state(addr, p2p::State::Defunct); } }) .expect("failed to launch peer_connect thread"); } // shrink the connecting history. // put a threshold here to avoid frequent shrinking in every call if connecting_history.len() > 100 { let now = Utc::now(); let old: Vec<_> = connecting_history .iter() .filter(|&(_, t)| *t + Duration::seconds(connect_min_interval) < now) .map(|(s, _)| s.clone()) .collect(); for addr in old { connecting_history.remove(&addr); } } } pub fn dns_seeds() -> Box<dyn Fn() -> Vec<PeerAddr> + Send> { Box::new(|| { let mut addresses: Vec<PeerAddr> = vec![]; let net_seeds = if global::is_floonet() { FLOONET_DNS_SEEDS } else { MAINNET_DNS_SEEDS }; for dns_seed in net_seeds { let temp_addresses = addresses.clone(); debug!("Retrieving seed nodes from dns {}", dns_seed); match (dns_seed.to_owned(), 0).to_socket_addrs() { Ok(addrs) => addresses.append( &mut (addrs .map(|mut addr| { addr.set_port(if global::is_floonet() { 13414 } else { 3414 }); PeerAddr(addr) }) .filter(|addr| !temp_addresses.contains(addr)) .collect()), ), Err(e) => debug!("Failed to resolve seed {:?} got error {:?}", dns_seed, e), } } debug!("Retrieved seed addresses: {:?}", addresses); addresses }) } /// Convenience function when the seed list is immediately known. Mostly used /// for tests. pub fn predefined_seeds(addrs: Vec<PeerAddr>) -> Box<dyn Fn() -> Vec<PeerAddr> + Send> { Box::new(move || addrs.clone()) }
// Do not attempt any connection where is_known() fails for any reason. for p in new_peers { if let Ok(false) = peers.is_known(p.addr) {
scale_up.go
package actions import ( "context" "fmt" "github.com/pkg/errors" scyllav1 "github.com/scylladb/scylla-operator/pkg/api/v1" "github.com/scylladb/scylla-operator/pkg/controllers/cluster/util" "github.com/scylladb/scylla-operator/pkg/naming" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" ) const RackScaleUpAction = "rack-scale-up" // Implements Action interface var _ Action = &RackScaleUp{} type RackScaleUp struct { Rack scyllav1.RackSpec Cluster *scyllav1.ScyllaCluster } func
(r scyllav1.RackSpec, c *scyllav1.ScyllaCluster) *RackScaleUp { return &RackScaleUp{ Rack: r, Cluster: c, } } func (a *RackScaleUp) Name() string { return RackScaleUpAction } func (a *RackScaleUp) Execute(ctx context.Context, s *State) error { r, c := a.Rack, a.Cluster sts := &appsv1.StatefulSet{} err := s.Get(ctx, naming.NamespacedName(naming.StatefulSetNameForRack(r, c), c.Namespace), sts) if err != nil { return errors.Wrap(err, "failed to get statefulset") } if err = util.ScaleStatefulSet(ctx, sts, 1, s.kubeclient); err != nil { return errors.Wrap(err, "failed to scale statefulset") } // Record event for successful scale-up s.recorder.Event(c, corev1.EventTypeNormal, naming.SuccessSynced, fmt.Sprintf("Rack %s scaled up to %d members", r.Name, *sts.Spec.Replicas+1)) return nil }
NewRackScaleUpAction
_artifact.py
# # Copyright (C) 2020 Codethink Limited # Copyright (C) 2019 Bloomberg Finance LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Authors: # Tom Pollard <[email protected]> # Tristan Van Berkom <[email protected]> """ Artifact ========= Implementation of the Artifact class which aims to 'abstract' direct artifact composite interaction away from Element class """ import os from typing import Dict, Tuple from ._protos.buildstream.v2.artifact_pb2 import Artifact as ArtifactProto from . import _yaml from . import utils from .node import Node from .types import _Scope from .storage._casbaseddirectory import CasBasedDirectory from .sandbox._config import SandboxConfig from ._variables import Variables # An Artifact class to abstract artifact operations # from the Element class # # Args: # element (Element): The Element object # context (Context): The BuildStream context # strong_key (str): The elements strong cache key, dependent on context # strict_key (str): The elements strict cache key # weak_key (str): The elements weak cache key # class Artifact: version = 1
self._context = context self._cache_key = strong_key self._strict_key = strict_key self._weak_cache_key = weak_key self._artifactdir = context.artifactdir self._cas = context.get_cascache() self._tmpdir = context.tmpdir self._proto = None self._metadata_keys = None # Strong, strict and weak key tuple extracted from the artifact self._metadata_dependencies = None # Dictionary of dependency strong keys from the artifact self._metadata_workspaced = None # Boolean of whether it's a workspaced artifact self._metadata_workspaced_dependencies = None # List of which dependencies are workspaced from the artifact self._cached = None # Boolean of whether the artifact is cached # strong_key(): # # A property which evaluates to the strong key, regardless of whether # it was the strong key that the Artifact object was initialized with # or whether it was the strong key loaded from artifact metadata. # @property def strong_key(self) -> str: if self.cached(): key, _, _ = self.get_metadata_keys() else: key = self._cache_key return key # strict_key(): # # A property which evaluates to the strict key, regardless of whether # it was the strict key that the Artifact object was initialized with # or whether it was the strict key loaded from artifact metadata. # @property def strict_key(self) -> str: if self.cached(): _, key, _ = self.get_metadata_keys() else: key = self._strict_key return key # weak_key(): # # A property which evaluates to the weak key, regardless of whether # it was the weak key that the Artifact object was initialized with # or whether it was the weak key loaded from artifact metadata. # @property def weak_key(self) -> str: if self.cached(): _, _, key = self.get_metadata_keys() else: key = self._weak_cache_key return key # get_files(): # # Get a virtual directory for the artifact files content # # Returns: # (Directory): The virtual directory object # def get_files(self): files_digest = self._get_field_digest("files") return CasBasedDirectory(self._cas, digest=files_digest) # get_buildtree(): # # Get a virtual directory for the artifact buildtree content # # Returns: # (Directory): The virtual directory object # def get_buildtree(self): buildtree_digest = self._get_field_digest("buildtree") return CasBasedDirectory(self._cas, digest=buildtree_digest) # get_sources(): # # Get a virtual directory for the artifact sources # # Returns: # (Directory): The virtual directory object # def get_sources(self): sources_digest = self._get_field_digest("sources") return CasBasedDirectory(self._cas, digest=sources_digest) # get_logs(): # # Get the paths of the artifact's logs # # Returns: # (list): A list of object paths # def get_logs(self): artifact = self._get_proto() logfile_paths = [] for logfile in artifact.logs: logfile_paths.append(self._cas.objpath(logfile.digest)) return logfile_paths # get_extract_key(): # # Get the key used to extract the artifact # # Returns: # (str): The key # def get_extract_key(self): return self._cache_key or self._weak_cache_key # cache(): # # Create the artifact and commit to cache # # Args: # sandbox_build_dir (Directory): Virtual Directory object for the sandbox build-root # collectvdir (Directory): Virtual Directoy object from within the sandbox for collection # sourcesvdir (Directory): Virtual Directoy object for the staged sources # buildresult (tuple): bool, short desc and detailed desc of result # publicdata (dict): dict of public data to commit to artifact metadata # variables (Variables): The element's Variables # environment (dict): dict of the element's environment variables # sandboxconfig (SandboxConfig): The element's SandboxConfig # # Returns: # (int): The size of the newly cached artifact # def cache( self, *, sandbox_build_dir, collectvdir, sourcesvdir, buildresult, publicdata, variables, environment, sandboxconfig, ): context = self._context element = self._element size = 0 filesvdir = None buildtreevdir = None artifact = ArtifactProto() artifact.version = self.version # Store result artifact.build_success = buildresult[0] artifact.build_error = buildresult[1] artifact.build_error_details = "" if not buildresult[2] else buildresult[2] # Store keys artifact.strong_key = self._cache_key artifact.strict_key = self._strict_key artifact.weak_key = self._weak_cache_key artifact.was_workspaced = bool(element._get_workspace()) properties = ["mtime"] if artifact.was_workspaced else [] # Store files if collectvdir is not None: filesvdir = CasBasedDirectory(cas_cache=self._cas) filesvdir._import_files_internal(collectvdir, properties=properties) artifact.files.CopyFrom(filesvdir._get_digest()) size += filesvdir._get_size() # Store public data with utils._tempnamedfile_name(dir=self._tmpdir) as tmpname: _yaml.roundtrip_dump(publicdata, tmpname) public_data_digest = self._cas.add_object(path=tmpname) artifact.public_data.CopyFrom(public_data_digest) size += public_data_digest.size_bytes # Store low diversity metadata, this metadata must have a high # probability of deduplication, such as environment variables # and SandboxConfig. # with utils._tempnamedfile_name(dir=self._tmpdir) as tmpname: sandbox_dict = sandboxconfig.to_dict() low_diversity_dict = {"environment": environment, "sandbox-config": sandbox_dict} low_diversity_node = Node.from_dict(low_diversity_dict) _yaml.roundtrip_dump(low_diversity_node, tmpname) low_diversity_meta_digest = self._cas.add_object(path=tmpname) artifact.low_diversity_meta.CopyFrom(low_diversity_meta_digest) size += low_diversity_meta_digest.size_bytes # Store high diversity metadata, this metadata is expected to diverge # for every element and as such cannot be deduplicated. # with utils._tempnamedfile_name(dir=self._tmpdir) as tmpname: # The Variables object supports being converted directly to a dictionary variables_dict = dict(variables) high_diversity_dict = {"variables": variables_dict} high_diversity_node = Node.from_dict(high_diversity_dict) _yaml.roundtrip_dump(high_diversity_node, tmpname) high_diversity_meta_digest = self._cas.add_object(path=tmpname) artifact.high_diversity_meta.CopyFrom(high_diversity_meta_digest) size += high_diversity_meta_digest.size_bytes # store build dependencies for e in element._dependencies(_Scope.BUILD): new_build = artifact.build_deps.add() new_build.project_name = e.project_name new_build.element_name = e.name new_build.cache_key = e._get_cache_key() new_build.was_workspaced = bool(e._get_workspace()) # Store log file log_filename = context.messenger.get_log_filename() if log_filename: digest = self._cas.add_object(path=log_filename) log = artifact.logs.add() log.name = os.path.basename(log_filename) log.digest.CopyFrom(digest) size += log.digest.size_bytes # Store build tree if sandbox_build_dir is not None: buildtreevdir = CasBasedDirectory(cas_cache=self._cas) buildtreevdir._import_files_internal(sandbox_build_dir, properties=properties) artifact.buildtree.CopyFrom(buildtreevdir._get_digest()) size += buildtreevdir._get_size() # Store sources if sourcesvdir is not None: artifact.sources.CopyFrom(sourcesvdir._get_digest()) size += sourcesvdir._get_size() os.makedirs(os.path.dirname(os.path.join(self._artifactdir, element.get_artifact_name())), exist_ok=True) keys = utils._deduplicate([self._cache_key, self._weak_cache_key]) for key in keys: path = os.path.join(self._artifactdir, element.get_artifact_name(key=key)) with utils.save_file_atomic(path, mode="wb") as f: f.write(artifact.SerializeToString()) return size # cached_buildtree() # # Check if artifact is cached with expected buildtree. A # buildtree will not be present if the rest of the partial artifact # is not cached. # # Returns: # (bool): True if artifact cached with buildtree, False if # missing expected buildtree. Note this only confirms # if a buildtree is present, not its contents. # def cached_buildtree(self): buildtree_digest = self._get_field_digest("buildtree") if buildtree_digest: return self._cas.contains_directory(buildtree_digest, with_files=True) else: return False # buildtree_exists() # # Check if artifact was created with a buildtree. This does not check # whether the buildtree is present in the local cache. # # Returns: # (bool): True if artifact was created with buildtree # def buildtree_exists(self): artifact = self._get_proto() return bool(str(artifact.buildtree)) # cached_sources() # # Check if artifact is cached with sources. # # Returns: # (bool): True if artifact is cached with sources, False if sources # are not available. # def cached_sources(self): sources_digest = self._get_field_digest("sources") if sources_digest: return self._cas.contains_directory(sources_digest, with_files=True) else: return False # load_public_data(): # # Loads the public data from the cached artifact # # Returns: # (dict): The artifacts cached public data # def load_public_data(self): # Load the public data from the artifact artifact = self._get_proto() with self._cas.open(artifact.public_data) as meta_file: meta_str = meta_file.read() data = _yaml.load_data(meta_str, file_name="public.yaml") return data # load_sandbox_config(): # # Loads the sandbox configuration from the cached artifact # # Returns: # The stored SandboxConfig object # def load_sandbox_config(self) -> SandboxConfig: # Load the sandbox data from the artifact artifact = self._get_proto() meta_file = self._cas.objpath(artifact.low_diversity_meta) data = _yaml.load(meta_file, shortname="low-diversity-meta.yaml") # Extract the sandbox data config = data.get_mapping("sandbox-config") # Return a SandboxConfig return SandboxConfig.new_from_node(config) # load_environment(): # # Loads the environment variables from the cached artifact # # Returns: # The environment variables # def load_environment(self) -> Dict[str, str]: # Load the sandbox data from the artifact artifact = self._get_proto() meta_file = self._cas.objpath(artifact.low_diversity_meta) data = _yaml.load(meta_file, shortname="low-diversity-meta.yaml") # Extract the environment config = data.get_mapping("environment") # Return the environment return config.strip_node_info() # load_variables(): # # Loads the element variables from the cached artifact # # Returns: # The element variables # def load_variables(self) -> Variables: # Load the sandbox data from the artifact artifact = self._get_proto() meta_file = self._cas.objpath(artifact.high_diversity_meta) data = _yaml.load(meta_file, shortname="high-diversity-meta.yaml") # Extract the variables node and return the new Variables instance variables_node = data.get_mapping("variables") return Variables(variables_node) # load_build_result(): # # Load the build result from the cached artifact # # Returns: # (bool): Whether the artifact of this element present in the artifact cache is of a success # (str): Short description of the result # (str): Detailed description of the result # def load_build_result(self): artifact = self._get_proto() build_result = (artifact.build_success, artifact.build_error, artifact.build_error_details) return build_result # get_metadata_keys(): # # Retrieve the strong and weak keys from the given artifact. # # Returns: # The strong key # The strict key # The weak key # def get_metadata_keys(self) -> Tuple[str, str, str]: if self._metadata_keys is not None: return self._metadata_keys # Extract proto artifact = self._get_proto() strong_key = artifact.strong_key strict_key = artifact.strict_key weak_key = artifact.weak_key self._metadata_keys = (strong_key, strict_key, weak_key) return self._metadata_keys # get_metadata_workspaced(): # # Retrieve the hash of dependency from the given artifact. # # Returns: # (bool): Whether the given artifact was workspaced # def get_metadata_workspaced(self): if self._metadata_workspaced is not None: return self._metadata_workspaced # Extract proto artifact = self._get_proto() self._metadata_workspaced = artifact.was_workspaced return self._metadata_workspaced # get_metadata_workspaced_dependencies(): # # Retrieve the hash of workspaced dependencies keys from the given artifact. # # Returns: # (list): List of which dependencies are workspaced # def get_metadata_workspaced_dependencies(self): if self._metadata_workspaced_dependencies is not None: return self._metadata_workspaced_dependencies # Extract proto artifact = self._get_proto() self._metadata_workspaced_dependencies = [ dep.element_name for dep in artifact.build_deps if dep.was_workspaced ] return self._metadata_workspaced_dependencies # get_dependency_artifact_names() # # Retrieve the artifact names of all of the dependencies in _Scope.BUILD # # Returns: # (list [str]): A list of refs of all build dependencies in staging order. # def get_dependency_artifact_names(self): # XXX: The pylint disable is necessary due to upstream issue: # https://github.com/PyCQA/pylint/issues/850 from .element import _get_normal_name # pylint: disable=cyclic-import artifact = self._get_proto() try: dependency_refs = [ os.path.join(dep.project_name, _get_normal_name(dep.element_name), dep.cache_key) for dep in artifact.build_deps ] except AttributeError: # If the artifact has no dependencies, the build_deps attribute # will be missing from the proto. dependency_refs = [] return dependency_refs # query_cache(): # # Check whether the artifact corresponding to the stored cache key is # available. This also checks whether all required parts of the artifact # are available, which may depend on command and configuration. The cache # key used for querying is dependent on the current context. # # Returns: # (bool): Whether artifact is in local cache # def query_cache(self): artifact = self._load_proto() if not artifact: self._cached = False return False # Check whether 'files' subdirectory is available, with or without file contents if str(artifact.files) and not self._cas.contains_directory(artifact.files, with_files=True): self._cached = False return False # Check whether public data and logs are available logfile_digests = [logfile.digest for logfile in artifact.logs] digests = [artifact.low_diversity_meta, artifact.high_diversity_meta, artifact.public_data] + logfile_digests if not self._cas.contains_files(digests): self._cached = False return False self._proto = artifact self._cached = True return True # cached() # # Return whether the artifact is available in the local cache. This must # be called after `query_cache()` or `set_cached()`. # # Returns: # (bool): Whether artifact is in local cache # def cached(self, *, buildtree=False): assert self._cached is not None ret = self._cached if buildtree: ret = ret and (self.cached_buildtree() or not self.buildtree_exists()) return ret # cached_logs() # # Check if the artifact is cached with log files. # # Returns: # (bool): True if artifact is cached with logs, False if # element not cached or missing logs. # def cached_logs(self): # Log files are currently considered an essential part of an artifact. # If the artifact is cached, its log files are available as well. return self._element._cached() # set_cached() # # Mark the artifact as cached without querying the filesystem. # This is used as optimization when we know the artifact is available. # def set_cached(self): self._proto = self._load_proto() assert self._proto self._cached = True # pull() # # Pull artifact from remote artifact repository into local artifact cache. # # Args: # pull_buildtrees (bool): Whether to pull buildtrees or not # # Returns: True if the artifact has been downloaded, False otherwise # def pull(self, *, pull_buildtrees): artifacts = self._context.artifactcache pull_key = self.get_extract_key() if not artifacts.pull(self._element, pull_key, pull_buildtrees=pull_buildtrees): return False self.set_cached() # Add reference for the other key (weak key when pulling with strong key, # strong key when pulling with weak key) for key in self.get_metadata_keys(): artifacts.link_key(self._element, pull_key, key) return True # load_proto() # # Returns: # (Artifact): Artifact proto # def _load_proto(self): key = self.get_extract_key() proto_path = os.path.join(self._artifactdir, self._element.get_artifact_name(key=key)) artifact = ArtifactProto() try: with open(proto_path, mode="r+b") as f: artifact.ParseFromString(f.read()) except FileNotFoundError: return None os.utime(proto_path) return artifact # _get_proto() # # Returns: # (Artifact): Artifact proto # def _get_proto(self): return self._proto # _get_field_digest() # # Returns: # (Digest): Digest of field specified # def _get_field_digest(self, field): artifact_proto = self._get_proto() digest = getattr(artifact_proto, field) if not str(digest): return None return digest
def __init__(self, element, context, *, strong_key=None, strict_key=None, weak_key=None): self._element = element
0216_combination_sum_3.py
class Solution: def __init__(self): self.combs = [] def _backtrack(self, candidates, cur, target, k): if len(cur) == k and sum(cur) == target: self.combs.append(cur[:]) return if sum(cur) > target: return elif len(cur) < k: for idx, candi in enumerate(candidates): cur.append(candi) self._backtrack(candidates[idx + 1:], cur, target, k) # backtracking cur.pop() def
(self, k: int, n: int) -> list: self._backtrack(range(1, 10), [], n, k) return self.combs
combinationSum3
services.go
package apimanagement // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // ServicesClient is the apiManagement Client type ServicesClient struct { BaseClient } // NewServicesClient creates an instance of the ServicesClient client. func NewServicesClient(subscriptionID string) ServicesClient { return NewServicesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewServicesClientWithBaseURI creates an instance of the ServicesClient client using a custom endpoint. Use this // when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewServicesClientWithBaseURI(baseURI string, subscriptionID string) ServicesClient { return ServicesClient{NewWithBaseURI(baseURI, subscriptionID)} } // Backup creates a backup of the API Management service to the given Azure Storage Account. This is long running // operation and could take several minutes to complete. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // parameters - parameters supplied to the ApiManagementServices_Backup operation. func (client ServicesClient) Backup(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceBackupRestoreParameters) (result ServicesBackupFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Backup") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.StorageAccount", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.AccessKey", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.ContainerName", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.BackupName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "Backup", err.Error()) } req, err := client.BackupPreparer(ctx, resourceGroupName, serviceName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Backup", nil, "Failure preparing request") return } result, err = client.BackupSender(req) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Backup", nil, "Failure sending request") return } return } // BackupPreparer prepares the Backup request. func (client ServicesClient) BackupPreparer(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceBackupRestoreParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/backup", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // BackupSender sends the Backup request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) BackupSender(req *http.Request) (future ServicesBackupFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // BackupResponder handles the response to the Backup request. The method always // closes the http.Response Body. func (client ServicesClient) BackupResponder(resp *http.Response) (result ServiceResource, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // CheckNameAvailability checks availability and correctness of a name for an API Management service. // Parameters: // parameters - parameters supplied to the CheckNameAvailability operation. func (client ServicesClient) CheckNameAvailability(ctx context.Context, parameters ServiceCheckNameAvailabilityParameters) (result ServiceNameAvailabilityResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.CheckNameAvailability") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Name", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "CheckNameAvailability", err.Error()) } req, err := client.CheckNameAvailabilityPreparer(ctx, parameters) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "CheckNameAvailability", nil, "Failure preparing request") return } resp, err := client.CheckNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "CheckNameAvailability", resp, "Failure sending request") return } result, err = client.CheckNameAvailabilityResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "CheckNameAvailability", resp, "Failure responding to request") return } return } // CheckNameAvailabilityPreparer prepares the CheckNameAvailability request. func (client ServicesClient) CheckNameAvailabilityPreparer(ctx context.Context, parameters ServiceCheckNameAvailabilityParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ApiManagement/checkNameAvailability", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CheckNameAvailabilitySender sends the CheckNameAvailability request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) CheckNameAvailabilitySender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // CheckNameAvailabilityResponder handles the response to the CheckNameAvailability request. The method always // closes the http.Response Body. func (client ServicesClient) CheckNameAvailabilityResponder(resp *http.Response) (result ServiceNameAvailabilityResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // CreateOrUpdate creates or updates an API Management service. This is long running operation and could take several // minutes to complete. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // parameters - parameters supplied to the CreateOrUpdate API Management service operation. func (client ServicesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceResource) (result ServiceResource, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.CreateOrUpdate") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Location", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "CreateOrUpdate", err.Error()) } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, serviceName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "CreateOrUpdate", nil, "Failure preparing request") return } resp, err := client.CreateOrUpdateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "CreateOrUpdate", resp, "Failure sending request") return } result, err = client.CreateOrUpdateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "CreateOrUpdate", resp, "Failure responding to request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client ServicesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceResource) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } parameters.ID = nil parameters.Name = nil parameters.Type = nil preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client ServicesClient) CreateOrUpdateResponder(resp *http.Response) (result ServiceResource, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes an existing API Management service. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. func (client ServicesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string) (result ErrorResponse, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Delete") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "Delete", err.Error()) } req, err := client.DeletePreparer(ctx, resourceGroupName, serviceName) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Delete", nil, "Failure preparing request") return } resp, err := client.DeleteSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Delete", resp, "Failure sending request") return } result, err = client.DeleteResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Delete", resp, "Failure responding to request") return } return } // DeletePreparer prepares the Delete request. func (client ServicesClient) DeletePreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) DeleteSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client ServicesClient) DeleteResponder(resp *http.Response) (result ErrorResponse, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent, http.StatusNotFound), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Get gets an API Management service resource description. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. func (client ServicesClient) Get(ctx context.Context, resourceGroupName string, serviceName string) (result SetObject, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, resourceGroupName, serviceName) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client ServicesClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client ServicesClient) GetResponder(resp *http.Response) (result SetObject, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNotFound), autorest.ByUnmarshallingJSON(&result.Value), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // GetSsoToken gets the Single-Sign-On token for the API Management Service which is valid for 5 Minutes. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. func (client ServicesClient) GetSsoToken(ctx context.Context, resourceGroupName string, serviceName string) (result ServiceGetSsoTokenResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.GetSsoToken") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "GetSsoToken", err.Error()) } req, err := client.GetSsoTokenPreparer(ctx, resourceGroupName, serviceName) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "GetSsoToken", nil, "Failure preparing request") return } resp, err := client.GetSsoTokenSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "GetSsoToken", resp, "Failure sending request") return } result, err = client.GetSsoTokenResponder(resp) if err != nil
return } // GetSsoTokenPreparer prepares the GetSsoToken request. func (client ServicesClient) GetSsoTokenPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/getssotoken", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSsoTokenSender sends the GetSsoToken request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) GetSsoTokenSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetSsoTokenResponder handles the response to the GetSsoToken request. The method always // closes the http.Response Body. func (client ServicesClient) GetSsoTokenResponder(resp *http.Response) (result ServiceGetSsoTokenResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List lists all API Management services within an Azure subscription. func (client ServicesClient) List(ctx context.Context) (result ServiceListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.List") defer func() { sc := -1 if result.slr.Response.Response != nil { sc = result.slr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.slr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "List", resp, "Failure sending request") return } result.slr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "List", resp, "Failure responding to request") return } if result.slr.hasNextLink() && result.slr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListPreparer prepares the List request. func (client ServicesClient) ListPreparer(ctx context.Context) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ApiManagement/service/", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client ServicesClient) ListResponder(resp *http.Response) (result ServiceListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client ServicesClient) listNextResults(ctx context.Context, lastResults ServiceListResult) (result ServiceListResult, err error) { req, err := lastResults.serviceListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client ServicesClient) ListComplete(ctx context.Context) (result ServiceListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx) return } // ListByResourceGroup list all API Management services within a resource group. // Parameters: // resourceGroupName - the name of the resource group. func (client ServicesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ServiceListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.ListByResourceGroup") defer func() { sc := -1 if result.slr.Response.Response != nil { sc = result.slr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listByResourceGroupNextResults req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "ListByResourceGroup", nil, "Failure preparing request") return } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.slr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "ListByResourceGroup", resp, "Failure sending request") return } result.slr, err = client.ListByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "ListByResourceGroup", resp, "Failure responding to request") return } if result.slr.hasNextLink() && result.slr.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListByResourceGroupPreparer prepares the ListByResourceGroup request. func (client ServicesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always // closes the http.Response Body. func (client ServicesClient) ListByResourceGroupResponder(resp *http.Response) (result ServiceListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByResourceGroupNextResults retrieves the next set of results, if any. func (client ServicesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ServiceListResult) (result ServiceListResult, err error) { req, err := lastResults.serviceListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") } result, err = client.ListByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") } return } // ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. func (client ServicesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ServiceListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.ListByResourceGroup") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) return } // ManageDeployments manages deployments of an API Management service. This operation can be used to do the following: // Change SKU, Change SKU Units, Change Service Tier (Developer/Standard/Premium) and Manage VPN Configuration. This is // a long running operation and can take several minutes to complete. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // parameters - parameters supplied to the ManageDeployments operation. func (client ServicesClient) ManageDeployments(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceManageDeploymentsParameters) (result ServicesManageDeploymentsFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.ManageDeployments") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Location", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "ManageDeployments", err.Error()) } req, err := client.ManageDeploymentsPreparer(ctx, resourceGroupName, serviceName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "ManageDeployments", nil, "Failure preparing request") return } result, err = client.ManageDeploymentsSender(req) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "ManageDeployments", nil, "Failure sending request") return } return } // ManageDeploymentsPreparer prepares the ManageDeployments request. func (client ServicesClient) ManageDeploymentsPreparer(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceManageDeploymentsParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/managedeployments", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ManageDeploymentsSender sends the ManageDeployments request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) ManageDeploymentsSender(req *http.Request) (future ServicesManageDeploymentsFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // ManageDeploymentsResponder handles the response to the ManageDeployments request. The method always // closes the http.Response Body. func (client ServicesClient) ManageDeploymentsResponder(resp *http.Response) (result ServiceResource, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Restore restores a backup of an API Management service created using the ApiManagementServices_Backup operation on // the current service. This is a long running operation and could take several minutes to complete. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // parameters - parameters supplied to the Restore API Management service from backup operation. func (client ServicesClient) Restore(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceBackupRestoreParameters) (result ServicesRestoreFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Restore") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.StorageAccount", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.AccessKey", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.ContainerName", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.BackupName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "Restore", err.Error()) } req, err := client.RestorePreparer(ctx, resourceGroupName, serviceName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Restore", nil, "Failure preparing request") return } result, err = client.RestoreSender(req) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Restore", nil, "Failure sending request") return } return } // RestorePreparer prepares the Restore request. func (client ServicesClient) RestorePreparer(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceBackupRestoreParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/restore", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // RestoreSender sends the Restore request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) RestoreSender(req *http.Request) (future ServicesRestoreFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // RestoreResponder handles the response to the Restore request. The method always // closes the http.Response Body. func (client ServicesClient) RestoreResponder(resp *http.Response) (result ServiceResource, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Update updates an existing API Management service. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // parameters - parameters supplied to the CreateOrUpdate API Management service operation. func (client ServicesClient) Update(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceBaseParameters) (result ServicesUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.Update") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "Update", err.Error()) } req, err := client.UpdatePreparer(ctx, resourceGroupName, serviceName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Update", nil, "Failure preparing request") return } result, err = client.UpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "Update", nil, "Failure sending request") return } return } // UpdatePreparer prepares the Update request. func (client ServicesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceBaseParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) UpdateSender(req *http.Request) (future ServicesUpdateFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client ServicesClient) UpdateResponder(resp *http.Response) (result ServiceResource, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // UpdateHostname creates, updates, or deletes the custom hostnames for an API Management service. The custom hostname // can be applied to the Proxy and Portal endpoint. This is a long running operation and could take several minutes to // complete. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // parameters - parameters supplied to the UpdateHostname operation. func (client ServicesClient) UpdateHostname(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceUpdateHostnameParameters) (result ServicesUpdateHostnameFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.UpdateHostname") defer func() { sc := -1 if result.FutureAPI != nil && result.FutureAPI.Response() != nil { sc = result.FutureAPI.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "UpdateHostname", err.Error()) } req, err := client.UpdateHostnamePreparer(ctx, resourceGroupName, serviceName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "UpdateHostname", nil, "Failure preparing request") return } result, err = client.UpdateHostnameSender(req) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "UpdateHostname", nil, "Failure sending request") return } return } // UpdateHostnamePreparer prepares the UpdateHostname request. func (client ServicesClient) UpdateHostnamePreparer(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceUpdateHostnameParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/updatehostname", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateHostnameSender sends the UpdateHostname request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) UpdateHostnameSender(req *http.Request) (future ServicesUpdateHostnameFuture, err error) { var resp *http.Response resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } var azf azure.Future azf, err = azure.NewFutureFromResponse(resp) future.FutureAPI = &azf future.Result = future.result return } // UpdateHostnameResponder handles the response to the UpdateHostname request. The method always // closes the http.Response Body. func (client ServicesClient) UpdateHostnameResponder(resp *http.Response) (result ServiceResource, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // UploadCertificate upload Custom Domain SSL certificate for an API Management service. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // parameters - parameters supplied to the Upload SSL certificate for an API Management service operation. func (client ServicesClient) UploadCertificate(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceUploadCertificateParameters) (result CertificateInformation, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServicesClient.UploadCertificate") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}, {TargetValue: parameters, Constraints: []validation.Constraint{{Target: "parameters.Certificate", Name: validation.Null, Rule: true, Chain: nil}, {Target: "parameters.CertificatePassword", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.ServicesClient", "UploadCertificate", err.Error()) } req, err := client.UploadCertificatePreparer(ctx, resourceGroupName, serviceName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "UploadCertificate", nil, "Failure preparing request") return } resp, err := client.UploadCertificateSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "UploadCertificate", resp, "Failure sending request") return } result, err = client.UploadCertificateResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "UploadCertificate", resp, "Failure responding to request") return } return } // UploadCertificatePreparer prepares the UploadCertificate request. func (client ServicesClient) UploadCertificatePreparer(ctx context.Context, resourceGroupName string, serviceName string, parameters ServiceUploadCertificateParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2016-07-07" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/updatecertificate", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UploadCertificateSender sends the UploadCertificate request. The method will close the // http.Response Body if it receives an error. func (client ServicesClient) UploadCertificateSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // UploadCertificateResponder handles the response to the UploadCertificate request. The method always // closes the http.Response Body. func (client ServicesClient) UploadCertificateResponder(resp *http.Response) (result CertificateInformation, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
{ err = autorest.NewErrorWithError(err, "apimanagement.ServicesClient", "GetSsoToken", resp, "Failure responding to request") return }
gatsby-config.js
module.exports = { pathPrefix: '/gatsby-react-bootstrap-starter', siteMetadata: { title: `Cat Quinn Yoga`, description: `A re-design project`, author: `Sandy` }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images` } }, { resolve: 'gatsby-background-image-es5', options: { specialChars: '/:' } }, `gatsby-plugin-sass`, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-react-bootstrap`, short_name: `react-bootstrap`, start_url: `/`, background_color: `#20232a`,
icon: `src/images/` } } ] }
theme_color: `#20232a`, display: `minimal-ui`,
pagebuilder.go
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package testutils import ( "encoding/binary" "io" "reflect" "github.com/apache/arrow/go/arrow/memory" "github.com/apache/arrow/go/parquet" "github.com/apache/arrow/go/parquet/compress" "github.com/apache/arrow/go/parquet/file" "github.com/apache/arrow/go/parquet/internal/encoding" "github.com/apache/arrow/go/parquet/internal/utils" "github.com/apache/arrow/go/parquet/schema" "github.com/stretchr/testify/mock" ) type DataPageBuilder struct { sink io.Writer version parquet.DataPageVersion nvals int encoding parquet.Encoding defLvlEncoding parquet.Encoding repLvlEncoding parquet.Encoding defLvlBytesLen int repLvlBytesLen int hasDefLvls bool hasRepLvls bool hasValues bool } var mem = memory.NewGoAllocator() func (d *DataPageBuilder) appendLevels(lvls []int16, maxLvl int16, e parquet.Encoding) int { if e != parquet.Encodings.RLE { panic("parquet: only rle encoding currently implemented") } buf := encoding.NewBufferWriter(encoding.LevelEncodingMaxBufferSize(e, maxLvl, len(lvls)), memory.DefaultAllocator) var enc encoding.LevelEncoder enc.Init(e, maxLvl, buf) enc.Encode(lvls) rleBytes := enc.Len() if d.version == parquet.DataPageV1 { if err := binary.Write(d.sink, binary.LittleEndian, int32(rleBytes)); err != nil { panic(err) } } if _, err := d.sink.Write(buf.Bytes()[:rleBytes]); err != nil { panic(err) } return rleBytes } func (d *DataPageBuilder) AppendDefLevels(lvls []int16, maxLvl int16) { d.defLvlBytesLen = d.appendLevels(lvls, maxLvl, parquet.Encodings.RLE) d.nvals = utils.MaxInt(len(lvls), d.nvals) d.defLvlEncoding = parquet.Encodings.RLE d.hasDefLvls = true } func (d *DataPageBuilder) AppendRepLevels(lvls []int16, maxLvl int16) { d.repLvlBytesLen = d.appendLevels(lvls, maxLvl, parquet.Encodings.RLE) d.nvals = utils.MaxInt(len(lvls), d.nvals) d.repLvlEncoding = parquet.Encodings.RLE d.hasRepLvls = true } func (d *DataPageBuilder) AppendValues(desc *schema.Column, values interface{}, e parquet.Encoding) { enc := encoding.NewEncoder(desc.PhysicalType(), e, false, desc, mem) var sz int switch v := values.(type) { case []int32: enc.(encoding.Int32Encoder).Put(v) sz = len(v) case []int64: enc.(encoding.Int64Encoder).Put(v) sz = len(v) case []parquet.Int96: enc.(encoding.Int96Encoder).Put(v) sz = len(v) case []float32: enc.(encoding.Float32Encoder).Put(v) sz = len(v) case []float64: enc.(encoding.Float64Encoder).Put(v) sz = len(v) case []parquet.ByteArray: enc.(encoding.ByteArrayEncoder).Put(v) sz = len(v) } buf, _ := enc.FlushValues() _, err := d.sink.Write(buf.Bytes()) if err != nil { panic(err) } d.nvals = utils.MaxInt(sz, d.nvals) d.encoding = e d.hasValues = true } type DictionaryPageBuilder struct { traits encoding.DictEncoder numDictValues int32 hasValues bool } func NewDictionaryPageBuilder(d *schema.Column) *DictionaryPageBuilder
func (d *DictionaryPageBuilder) AppendValues(values interface{}) encoding.Buffer { switch v := values.(type) { case []int32: d.traits.(encoding.Int32Encoder).Put(v) case []int64: d.traits.(encoding.Int64Encoder).Put(v) case []parquet.Int96: d.traits.(encoding.Int96Encoder).Put(v) case []float32: d.traits.(encoding.Float32Encoder).Put(v) case []float64: d.traits.(encoding.Float64Encoder).Put(v) case []parquet.ByteArray: d.traits.(encoding.ByteArrayEncoder).Put(v) } d.numDictValues = int32(d.traits.NumEntries()) d.hasValues = true buf, _ := d.traits.FlushValues() return buf } func (d *DictionaryPageBuilder) WriteDict() *memory.Buffer { buf := memory.NewBufferBytes(make([]byte, d.traits.DictEncodedSize())) d.traits.WriteDict(buf.Bytes()) return buf } func (d *DictionaryPageBuilder) NumValues() int32 { return d.numDictValues } func MakeDataPage(dataPageVersion parquet.DataPageVersion, d *schema.Column, values interface{}, nvals int, e parquet.Encoding, indexBuffer encoding.Buffer, defLvls, repLvls []int16, maxDef, maxRep int16) file.Page { num := 0 stream := encoding.NewBufferWriter(1024, mem) builder := DataPageBuilder{sink: stream, version: dataPageVersion} if len(repLvls) > 0 { builder.AppendRepLevels(repLvls, maxRep) } if len(defLvls) > 0 { builder.AppendDefLevels(defLvls, maxDef) } if e == parquet.Encodings.Plain { builder.AppendValues(d, values, e) num = builder.nvals } else { stream.Write(indexBuffer.Bytes()) num = utils.MaxInt(builder.nvals, nvals) } buf := stream.Finish() if dataPageVersion == parquet.DataPageV1 { return file.NewDataPageV1(buf, int32(num), e, builder.defLvlEncoding, builder.repLvlEncoding, int64(buf.Len())) } return file.NewDataPageV2(buf, int32(num), 0, int32(num), e, int32(builder.defLvlBytesLen), int32(builder.repLvlBytesLen), int64(buf.Len()), false) } func MakeDictPage(d *schema.Column, values interface{}, valuesPerPage []int, e parquet.Encoding) (*file.DictionaryPage, []encoding.Buffer) { bldr := NewDictionaryPageBuilder(d) npages := len(valuesPerPage) ref := reflect.ValueOf(values) valStart := 0 rleIndices := make([]encoding.Buffer, 0, npages) for _, nvals := range valuesPerPage { rleIndices = append(rleIndices, bldr.AppendValues(ref.Slice(valStart, valStart+nvals).Interface())) valStart += nvals } buffer := bldr.WriteDict() return file.NewDictionaryPage(buffer, bldr.NumValues(), parquet.Encodings.Plain), rleIndices } type MockPageReader struct { mock.Mock curpage int } func (m *MockPageReader) Err() error { return m.Called().Error(0) } func (m *MockPageReader) Reset(parquet.ReaderAtSeeker, int64, compress.Compression, *file.CryptoContext) { } func (m *MockPageReader) SetMaxPageHeaderSize(int) {} func (m *MockPageReader) Page() file.Page { return m.TestData().Get("pages").Data().([]file.Page)[m.curpage-1] } func (m *MockPageReader) Next() bool { pageList := m.TestData().Get("pages").Data().([]file.Page) m.curpage++ return len(pageList) >= m.curpage } func PaginatePlain(version parquet.DataPageVersion, d *schema.Column, values reflect.Value, defLevels, repLevels []int16, maxDef, maxRep int16, lvlsPerPage int, valuesPerPage []int, enc parquet.Encoding) []file.Page { var ( npages = len(valuesPerPage) defLvlStart = 0 defLvlEnd = 0 repLvlStart = 0 repLvlEnd = 0 valueStart = 0 ) pageList := make([]file.Page, 0, npages) for i := 0; i < npages; i++ { if maxDef > 0 { defLvlStart = i * lvlsPerPage defLvlEnd = (i + 1) * lvlsPerPage } if maxRep > 0 { repLvlStart = i * lvlsPerPage repLvlEnd = (i + 1) * lvlsPerPage } page := MakeDataPage(version, d, values.Slice(valueStart, valueStart+valuesPerPage[i]).Interface(), valuesPerPage[i], enc, nil, defLevels[defLvlStart:defLvlEnd], repLevels[repLvlStart:repLvlEnd], maxDef, maxRep) valueStart += valuesPerPage[i] pageList = append(pageList, page) } return pageList } func PaginateDict(version parquet.DataPageVersion, d *schema.Column, values reflect.Value, defLevels, repLevels []int16, maxDef, maxRep int16, lvlsPerPage int, valuesPerPage []int, enc parquet.Encoding) []file.Page { var ( npages = len(valuesPerPage) pages = make([]file.Page, 0, npages) defStart = 0 defEnd = 0 repStart = 0 repEnd = 0 ) dictPage, rleIndices := MakeDictPage(d, values.Interface(), valuesPerPage, enc) pages = append(pages, dictPage) for i := 0; i < npages; i++ { if maxDef > 0 { defStart = i * lvlsPerPage defEnd = (i + 1) * lvlsPerPage } if maxRep > 0 { repStart = i * lvlsPerPage repEnd = (i + 1) * lvlsPerPage } page := MakeDataPage(version, d, nil, valuesPerPage[i], enc, rleIndices[i], defLevels[defStart:defEnd], repLevels[repStart:repEnd], maxDef, maxRep) pages = append(pages, page) } return pages }
{ return &DictionaryPageBuilder{ encoding.NewEncoder(d.PhysicalType(), parquet.Encodings.Plain, true, d, mem).(encoding.DictEncoder), 0, false} }
models.py
# noqa: D100 from dataclasses import dataclass from decimal import Decimal from typing import Optional @dataclass(frozen=True) class Country: """Represents a country. Attributes: id: The ID of the country. name: The name of the country. country_code: Alpha-2 codes used by the ISO 3166 standard. country_code_numeric: UN codes used by the ISO 3166 standard. country_code_iso3: Alpha-3 codes used by the ISO 3166 standard. """ id: int name: str country_code: str country_code_numeric: str country_code_iso3: str @dataclass(frozen=True) class Port: """A maritime facility where vessels can dock. Attributes: id: ID of the port. country_id: ID of the country the port is in. area_id: ID of the area the port is in. name: Name of the port. latitude: Latitude of the port. longitude: Longitude of the port. source: The source of information about the port. """ id: int country_id: int area_id: int name: str latitude: Decimal longitude: Decimal source: str @dataclass(frozen=True) class Area:
"""A geographical area. Attributes: id: ID of the area. name: Name of the area. area_type_id: ID of the area type. parent_area_id: ID of this area's parent area. None if the area has no parent. """ id: int name: str area_type_id: int parent_area_id: Optional[int]
behavior.js
export default class Behavior { constructor() { this.action = null this.subject = null
this.reply = null } getReply() { return this.reply } setReply(value) { this.reply = value return this } getSubject() { return this.subject } setSubject(value) { this.subject = value return this } getAction() { return this.action } setAction(value) { this.action = value return this } }
scalar.rs
//! Arithmetic mod `2^249 - 15145038707218910765482344729778085401` //! with five 52-bit unsigned limbs //! represented in radix `2^52`. use core::fmt::Debug; use core::ops::{Index, IndexMut}; use core::ops::{Add, Sub, Mul, Neg}; use std::cmp::{PartialOrd, Ordering, Ord}; use num::Integer; use crate::backend::u64::constants; use crate::traits::Identity; use crate::traits::ops::*; /// The `Scalar` struct represents an Scalar over the modulo /// `2^249 - 15145038707218910765482344729778085401` as 5 52-bit limbs /// represented in radix `2^52`. #[derive(Copy,Clone)] pub struct Scalar(pub [u64; 5]); impl Debug for Scalar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { write!(f, "Scalar: {:?}", &self.0[..]) } } impl Index<usize> for Scalar { type Output = u64; fn index(&self, _index: usize) -> &u64 { &(self.0[_index]) } } impl IndexMut<usize> for Scalar { fn index_mut(&mut self, _index: usize) -> &mut u64 { &mut (self.0[_index]) } } impl PartialOrd for Scalar { fn partial_cmp(&self, other: &Scalar) -> Option<Ordering> { Some(self.cmp(&other)) } } impl Ord for Scalar { fn cmp(&self, other: &Self) -> Ordering { for i in (0..5).rev() { if self[i] > other[i] { return Ordering::Greater; }else if self[i] < other[i] { return Ordering::Less; } } Ordering::Equal } } //-------------- From Implementations -----------------// impl<'a> From<&'a u8> for Scalar { /// Performs the conversion. fn from(_inp: &'a u8) -> Scalar { let mut res = Scalar::zero(); res[0] = *_inp as u64; res } } impl<'a> From<&'a u16> for Scalar { /// Performs the conversion. fn from(_inp: &'a u16) -> Scalar { let mut res = Scalar::zero(); res[0] = *_inp as u64; res } } impl<'a> From<&'a u32> for Scalar { /// Performs the conversion. fn from(_inp: &'a u32) -> Scalar { let mut res = Scalar::zero(); res[0] = *_inp as u64; res } } impl<'a> From<&'a u64> for Scalar { /// Performs the conversion. fn from(_inp: &'a u64) -> Scalar { let mut res = Scalar::zero(); let mask = (1u64 << 52) - 1; res[0] = _inp & mask; res[1] = _inp >> 52; res } } impl<'a> From<&'a u128> for Scalar { /// Performs the conversion. fn from(_inp: &'a u128) -> Scalar { let mut res = Scalar::zero(); let mask = (1u128 << 52) - 1; // Since 128 / 52 < 4 , we only need to care // about the first three limbs. res[0] = (_inp & mask) as u64; res[1] = ((_inp >> 52) & mask) as u64; res[2] = (_inp >> 104) as u64; res } } impl<'a> Neg for &'a Scalar { type Output = Scalar; /// Performs the negate operation over the /// sub-group modulo l. fn neg(self) -> Scalar { &Scalar::zero() - &self } } impl Neg for Scalar { type Output = Scalar; /// Performs the negate operation over the /// sub-group modulo l. fn neg(self) -> Scalar { -&self } } impl Identity for Scalar { /// Returns the `Identity` element for `Scalar` /// which equals `1 (mod l)`. fn identity() -> Scalar { Scalar::one() } } impl<'a, 'b> Add<&'b Scalar> for &'a Scalar { type Output = Scalar; /// Compute `a + b (mod l)`. fn add(self, b: &'b Scalar) -> Scalar { let mut sum = Scalar::zero(); let mask = (1u64 << 52) - 1; // a + b let mut carry: u64 = 0; for i in 0..5 { carry = self.0[i] + b[i] + (carry >> 52); sum[i] = carry & mask; } // subtract l if the sum is >= l sum - constants::L } } impl Add<Scalar> for Scalar { type Output = Scalar; /// Compute `a + b (mod l)`. fn add(self, b: Scalar) -> Scalar { &self + &b } } impl<'a, 'b> Sub<&'b Scalar> for &'a Scalar { type Output = Scalar; /// Compute `a - b (mod l)`. fn sub(self, b: &'b Scalar) -> Scalar { let mut difference = Scalar::zero(); let mask = (1u64 << 52) - 1; // a - b let mut borrow: u64 = 0; // Save the wrapping_sub in borrow and add the remainder to the next limb. for i in 0..5 { // Borrow >> 63 so the Most Significant Bit of the remainder (2^64) can be carried to the next limb. borrow = self.0[i].wrapping_sub(b[i] + (borrow >> 63)); difference[i] = borrow & mask; } // conditionally add `l` if the difference is negative. // Note that here borrow tells us the Most Signif Bit of the last limb so then we know if it's greater than `l`. let underflow_mask = ((borrow >> 63) ^ 1).wrapping_sub(1); // If isn't greater, we will not add it as XOR = 0. let mut carry: u64 = 0; for i in 0..5 { carry = (carry >> 52) + difference[i] + (constants::L[i] & underflow_mask); difference[i] = carry & mask; } difference } } impl Sub<Scalar> for Scalar { type Output = Scalar; /// Compute `a - b (mod l)`. fn sub(self, b: Scalar) -> Scalar { &self - &b } } impl<'a, 'b> Mul<&'a Scalar> for &'b Scalar { type Output = Scalar; /// This `Mul` implementation returns a double precision result. /// The result of the standard mul is stored on a [u128; 9]. /// /// Then, we apply the Montgomery Reduction function to perform /// the modulo and the reduction to the `Scalar` format: [u64; 5]. fn mul(self, b: &'a Scalar) -> Scalar { let ab = Scalar::montgomery_reduce(&Scalar::mul_internal(self, b)); Scalar::montgomery_reduce(&Scalar::mul_internal(&ab, &constants::RR)) } } impl Mul<Scalar> for Scalar { type Output = Scalar; /// This `Mul` implementation returns a double precision result. /// The result of the standard mul is stored on a [u128; 9]. /// /// Then, we apply the Montgomery Reduction function to perform /// the modulo and the reduction to the `Scalar` format: [u64; 5]. fn mul(self, b: Scalar) -> Scalar { &self * &b } } impl<'a> Square for &'a Scalar { type Output = Scalar; /// This `Square` implementation returns a double precision result. /// The result of the standard mul is stored on a [u128; 9]. /// /// Then, we apply the Montgomery Reduction function to perform /// the modulo and the reduction to the `Scalar` format: [u64; 5]. fn square(self) -> Scalar { let aa = Scalar::montgomery_reduce(&Scalar::square_internal(self)); Scalar::montgomery_reduce(&Scalar::mul_internal(&aa, &constants::RR)) } } impl<'a> Half for &'a Scalar { type Output = Scalar; /// Give the half of the Scalar value (mod l). /// /// This op **SHOULD ONLY** be used with even /// `Scalars` otherways, can produce erroneus /// results. /// /// The implementation for `Scalar` has indeed /// an `assert!` statement to check this. #[inline] fn half(self) -> Scalar { assert!(self.is_even(), "The Scalar has to be even."); let mut res = self.clone(); let mut remainder = 0u64; for i in (0..5).rev() { res[i] = res[i] + remainder; match(res[i] == 1, res[i].is_even()){ (true, _) => { remainder = 4503599627370496u64; } (_, false) => { res[i] = res[i] - 1u64; remainder = 4503599627370496u64; } (_, true) => { remainder = 0; } } res[i] = res[i] >> 1; }; res } } /// u64 * u64 = u128 inline func multiply helper. #[inline] fn m(x: u64, y: u64) -> u128 { (x as u128) * (y as u128) } /// u64 * u64 = u128 macro multiply helper macro_rules! m { ($x:expr, $y:expr) => { $x as u128 * $y as u128 } } impl Scalar { /// Return a Scalar with value = `0`. pub fn zero() -> Scalar { Scalar([0,0,0,0,0]) } /// Return a Scalar with value = `1`. pub fn one() -> Scalar { Scalar([1,0,0,0,0]) } /// Return a Scalar with value = `-1 (mod l)`. pub fn minus_one() -> Scalar { Scalar([2766226127823334, 4237835465749098, 4503599626623787, 4503599627370495, 2199023255551]) } /// Evaluate if a `Scalar` is even or not. pub fn is_even(self) -> bool
/// Unpack a 32 byte / 256 bit Scalar into 5 52-bit limbs. pub fn from_bytes(bytes: &[u8; 32]) -> Scalar { let mut words = [0u64; 4]; for i in 0..4 { for j in 0..8 { words[i] |= (bytes[(i * 8) + j] as u64) << (j * 8); } } let mask = (1u64 << 52) - 1; let top_mask = (1u64 << 48) - 1; let mut s = Scalar::zero(); s[0] = words[0] & mask; // Get the 64-52 = 12 bits and add words[1] (shifting 12 to the left) on the front with `|` then apply mask. s[1] = ((words[0] >> 52) | (words[1] << 12)) & mask; s[2] = ((words[1] >> 40) | (words[2] << 24)) & mask; s[3] = ((words[2] >> 28) | (words[3] << 36)) & mask; // Shift 16 to the right to get the 52 bits of the scalar on that limb. Then apply top_mask. s[4] = (words[3] >> 16) & top_mask; s } /// Reduce a 64 byte / 512 bit scalar mod l pub fn from_bytes_wide(_bytes: &[u8; 64]) -> Scalar { // We could provide 512 bit scalar support using Montgomery Reduction. // But first we need to finnish the 256-bit implementation. unimplemented!() } /// Pack the limbs of this `Scalar` into 32 bytes pub fn to_bytes(&self) -> [u8; 32] { let mut res = [0u8; 32]; res[0] = (self.0[0] >> 0) as u8; res[1] = (self.0[0] >> 8) as u8; res[2] = (self.0[0] >> 16) as u8; res[3] = (self.0[0] >> 24) as u8; res[4] = (self.0[0] >> 32) as u8; res[5] = (self.0[0] >> 40) as u8; res[6] = ((self.0[0] >> 48) | (self.0[1] << 4)) as u8; res[7] = (self.0[1] >> 4) as u8; res[8] = (self.0[1] >> 12) as u8; res[9] = (self.0[ 1] >> 20) as u8; res[10] = (self.0[ 1] >> 28) as u8; res[11] = (self.0[ 1] >> 36) as u8; res[12] = (self.0[ 1] >> 44) as u8; res[13] = (self.0[ 2] >> 0) as u8; res[14] = (self.0[ 2] >> 8) as u8; res[15] = (self.0[ 2] >> 16) as u8; res[16] = (self.0[ 2] >> 24) as u8; res[17] = (self.0[ 2] >> 32) as u8; res[18] = (self.0[ 2] >> 40) as u8; res[19] = ((self.0[ 2] >> 48) | (self.0[ 3] << 4)) as u8; res[20] = (self.0[ 3] >> 4) as u8; res[21] = (self.0[ 3] >> 12) as u8; res[22] = (self.0[ 3] >> 20) as u8; res[23] = (self.0[ 3] >> 28) as u8; res[24] = (self.0[ 3] >> 36) as u8; res[25] = (self.0[ 3] >> 44) as u8; res[26] = (self.0[ 4] >> 0) as u8; res[27] = (self.0[ 4] >> 8) as u8; res[28] = (self.0[ 4] >> 16) as u8; res[29] = (self.0[ 4] >> 24) as u8; res[30] = (self.0[ 4] >> 32) as u8; res[31] = (self.0[ 4] >> 40) as u8; // High bit should be zero. debug_assert!((res[31] & 0b1000_0000u8) == 0u8); res } /// Given a `k`: u64, compute `2^k` giving the resulting result /// as a `Scalar`. /// /// See that the input must be between the range => 0..250. /// /// NOTE: This function implements an `assert!` statement that /// checks the correctness of the exponent provided as param. pub fn two_pow_k(exp: &u64) -> Scalar { // Check that exp has to be less than 260. // Note that a Scalar can be as much // `2^249 - 15145038707218910765482344729778085401` so we pick // 250 knowing that 249 will be lower than the prime of the // sub group. assert!(exp < &253u64, "Exponent can't be greater than 260"); let mut res = Scalar::zero(); match exp { 0...51 => { res[0] = 1u64 << exp; }, 52...103 => { res[1] = 1u64 << (exp - 52); }, 104...155 => { res[2] = 1u64 << (exp - 104); }, 156...207 => { res[3] = 1u64 << (exp - 156); }, _ => { res[4] = 1u64 << (exp - 208); } } res } /// Compute `a * b`. /// Note that this is just the normal way of performing a product. /// This operation returns back a double precision result stored /// on a `[u128; 9] in order to avoid overflowings. #[inline] pub(self) fn mul_internal(a: &Scalar, b: &Scalar) -> [u128; 9] { let mut res = [0u128; 9]; res[0] = m(a[0],b[0]); res[1] = m(a[0],b[1]) + m(a[1],b[0]); res[2] = m(a[0],b[2]) + m(a[1],b[1]) + m(a[2],b[0]); res[3] = m(a[0],b[3]) + m(a[1],b[2]) + m(a[2],b[1]) + m(a[3],b[0]); res[4] = m(a[0],b[4]) + m(a[1],b[3]) + m(a[2],b[2]) + m(a[3],b[1]) + m(a[4],b[0]); res[5] = m(a[1],b[4]) + m(a[2],b[3]) + m(a[3],b[2]) + m(a[4],b[1]); res[6] = m(a[2],b[4]) + m(a[3],b[3]) + m(a[4],b[2]); res[7] = m(a[3],b[4]) + m(a[4],b[3]); res[8] = m(a[4],b[4]); res } #[allow(dead_code)] #[inline] /// Compute `a * b`. /// Note that this is just the normal way of performing a product. /// This operation returns back a double precision result stored /// on a `[u128; 9] in order to avoid overflowings. pub(self) fn mul_internal_macros(a: &Scalar, b: &Scalar) -> [u128; 9] { let mut res = [0u128; 9]; res[0] = m!(a[0],b[0]); res[1] = m!(a[0],b[1]) + m!(a[1],b[0]); res[2] = m!(a[0],b[2]) + m!(a[1],b[1]) + m!(a[2],b[0]); res[3] = m!(a[0],b[3]) + m!(a[1],b[2]) + m!(a[2],b[1]) + m!(a[3],b[0]); res[4] = m!(a[0],b[4]) + m!(a[1],b[3]) + m!(a[2],b[2]) + m!(a[3],b[1]) + m!(a[4],b[0]); res[5] = m!(a[1],b[4]) + m!(a[2],b[3]) + m!(a[3],b[2]) + m!(a[4],b[1]); res[6] = m!(a[2],b[4]) + m!(a[3],b[3]) + m!(a[4],b[2]); res[7] = m!(a[3],b[4]) + m!(a[4],b[3]); res[8] = m!(a[4],b[4]); res } /// Compute `a^2`. /// /// This operation returns a double precision result. /// So it gives back a `[u128; 9]` with the result of the squaring. #[inline] pub(self) fn square_internal(a: &Scalar) -> [u128; 9] { let a_sqrt = [ a[0]*2, a[1]*2, a[2]*2, a[3]*2, ]; [ m(a[0],a[0]), m(a_sqrt[0],a[1]), m(a_sqrt[0],a[2]) + m(a[1],a[1]), m(a_sqrt[0],a[3]) + m(a_sqrt[1],a[2]), m(a_sqrt[0],a[4]) + m(a_sqrt[1],a[3]) + m(a[2],a[2]), m(a_sqrt[1],a[4]) + m(a_sqrt[2],a[3]), m(a_sqrt[2],a[4]) + m(a[3],a[3]), m(a_sqrt[3],a[4]), m(a[4],a[4]) ] } /// Give the half of the Scalar value (mod l). /// /// This op **SHOULD NEVER** be used by the end-user /// since it's designed to allow some behaviours /// needed on certain points of algorithm implementations. #[inline] #[doc(hidden)] pub(crate) fn inner_half(self) -> Scalar { let mut res = self.clone(); let mut remainder = 0u64; for i in (0..5).rev() { res[i] = res[i] + remainder; match(res[i] == 1, res[i].is_even()){ (true, _) => { remainder = 4503599627370496u64; } (_, false) => { res[i] = res[i] - 1u64; remainder = 4503599627370496u64; } (_, true) => { remainder = 0; } } res[i] = res[i] >> 1; }; res } /// Compute `limbs/R` (mod l), where R is the Montgomery modulus 2^260 #[inline] pub(self) fn montgomery_reduce(limbs: &[u128; 9]) -> Scalar { #[inline] fn adjustment_fact(sum: u128) -> (u128, u64) { let p = (sum as u64).wrapping_mul(constants::LFACTOR) & ((1u64 << 52) - 1); ((sum + m(p,constants::L[0])) >> 52, p) } #[inline] fn montg_red_res(sum: u128) -> (u128, u64) { let w = (sum as u64) & ((1u64 << 52) - 1); (sum >> 52, w) } let l = &constants::L; // the first half computes the Montgomery adjustment factor n, and begins adding n*l to make limbs divisible by R let (carry, n0) = adjustment_fact( limbs[0]); let (carry, n1) = adjustment_fact(carry + limbs[1] + m(n0,l[1])); let (carry, n2) = adjustment_fact(carry + limbs[2] + m(n0,l[2]) + m(n1,l[1])); let (carry, n3) = adjustment_fact(carry + limbs[3] + m(n0,l[3]) + m(n1,l[2]) + m(n2,l[1])); let (carry, n4) = adjustment_fact(carry + limbs[4] + m(n0,l[4]) + m(n1,l[3]) + m(n2,l[2]) + m(n3,l[1])); // limbs is divisible by R now, so we can divide by R by simply storing the upper half as the result let (carry, r0) = montg_red_res(carry + limbs[5] + m(n1,l[4]) + m(n2,l[3]) + m(n3,l[2]) + m(n4,l[1])); let (carry, r1) = montg_red_res(carry + limbs[6] + m(n2,l[4]) + m(n3,l[3]) + m(n4,l[2])); let (carry, r2) = montg_red_res(carry + limbs[7] + m(n3,l[4]) + m(n4,l[3])); let (carry, r3) = montg_red_res(carry + limbs[8] + m(n4,l[4])); let r4 = carry as u64; // result may be >= r, so attempt to subtract l &Scalar([r0,r1,r2,r3,r4]) - l } /// Compute `(a * b) / R` (mod l), where R is the Montgomery modulus 2^260 #[inline] #[allow(dead_code)] pub(self) fn montgomery_mul(a: &Scalar, b: &Scalar) -> Scalar { Scalar::montgomery_reduce(&Scalar::mul_internal(a, b)) } /// Puts a Scalar into Montgomery form, i.e. computes `a*R (mod l)` #[inline] #[allow(dead_code)] pub(self) fn to_montgomery(&self) -> Scalar { Scalar::montgomery_mul(self, &constants::RR) } /// Takes a Scalar out of Montgomery form, i.e. computes `a/R (mod l)` #[inline] #[allow(dead_code)] pub(self) fn from_montgomery(&self) -> Scalar { let mut limbs = [0u128; 9]; for i in 0..5 { limbs[i] = self[i] as u128; } Scalar::montgomery_reduce(&limbs) } } #[cfg(test)] mod tests { use super::*; /// `A = 182687704666362864775460604089535377456991567872`. pub static A: Scalar = Scalar([0, 0, 0, 2, 0]); /// `B = 904625697166532776746648320197686575422163851717637391703244652875051672039` pub static B: Scalar = Scalar([2766226127823335, 4237835465749098, 4503599626623787, 4503599627370493, 2199023255551]); /// `AB = A - B = -904625697166532776746648320014998870755800986942176787613709275418060104167 (mod l)`. /// which is equal to: `365375409332725729550921208179070754913983135744`. pub static AB: Scalar = Scalar([0, 0, 0, 4, 0]); /// `BA = B - A = 904625697166532776746648320014998870755800986942176787613709275418060104167`. pub static BA: Scalar = Scalar([2766226127823335, 4237835465749098, 4503599626623787, 4503599627370491, 2199023255551]); /// `A * AB (mod l). Result expected of the product mentioned before. pub static A_TIMES_AB: [u128; 9] = [0,0,0,0,0,0,0,8,0]; /// `B * BA` computed in Sage limb by limb. (Since we don't have any other way to verify it.) pub static B_TIMES_BA: [u128; 9] = [7652006990252481706224970522225, 23445622381543053554951959203660, 42875199347605145563220777152894, 63086978359456741425512297249892, 58465604036906492621308128018971, 40583457398062310210466901672404, 20302216644276907411437105105337, 19807040628557059606945202184, 4835703278454118652313601]; /// A in Montgomery domain; `A_MONT = (A * R) (mod l) = 295345389055300509611653655730781949282003822754281035405592286100742960688` pub static A_MONT: Scalar = Scalar([946644518663728, 4368868487057990, 2524289321948647, 594442899788814, 717944870444]); /// `X = 1809251394333065553493296640760748560207343510400633813116524750123642650623` pub static X: Scalar = Scalar([4503599627370495, 4503599627370495, 4503599627370495, 4503599627370495, 4398046511103]); /// `Y = 717350576871794411262215878514291949349241575907629849852603275827191647632`. pub static Y: Scalar = Scalar([138340288859536, 461913478537005, 1182880083788836, 1688835920473363, 1743782656037]); /// `Y^2 (mod l) = 351405481126033478170820083848817267677692781462667634162278835827410585241`. pub static Y_SQ: Scalar = Scalar([2359521284310681, 3823495160731511, 2863901539039406, 2131140264591444, 854219405379]); /// `Y/2 = 358675288435897205631107939257145974674620787953814924926301637913595823816`. pub static Y_HALF: Scalar = Scalar([2320969958115016, 230956739268502, 2843239855579666, 3096217773921929, 871891328018]); /// Y in Montgomery domain; `Y_MONT = (Y * R) (mod l) = 682963356548663143913382285837893622221394109239214830065314998385324548003` pub static Y_MONT: Scalar = Scalar([2328716356837283, 1997480944140188, 4481133454453893, 3196446152249575, 1660191953914]); /// `(X * Y)/R (mod l) = 781842614815424000988673591006250240924873016371899513350486876443913409068` pub static X_TIMES_Y_MONT: Scalar = Scalar([1458967730377260, 963769115966027, 34859148282403, 2124040828839810, 1900554115968]); /// `X * Y (mod l) = 890263784947025690345271110799906008759402458672628420828189878638015362081` pub static X_TIMES_Y: Scalar = Scalar([3414372756436001, 1500062170770321, 4341044393209371, 2791496957276064, 2164111380879]); //------------------ Tests ------------------// #[test] fn partial_ord_and_eq() { assert!(Y.is_even()); assert!(!X.is_even()); assert!(A_MONT < Y); assert!(Y < X); assert!(Y >= Y); assert!(X == X); } #[test] fn add_with_modulo() { let res = A + B; let zero = Scalar::zero();; for i in 0..5 { assert!(res[i] == zero[i]); } } #[test] fn sub_with_modulo() { let res = A - B; for i in 0..5 { assert!(res[i] == AB[i]); } } #[test] fn sub_without_modulo() { let res = B - A; for i in 0..5 { assert!(res[i] == BA[i]); } } #[test] fn mul_internal() { let easy_res = Scalar::mul_internal(&A, &AB); for i in 0..5 { assert!(easy_res[i] == A_TIMES_AB[i]); } let res = Scalar::mul_internal(&B, &BA); for i in 0..9 { assert!(res[i] == B_TIMES_BA[i]); } } #[test] fn square_internal() { let easy_res = Scalar::square_internal(&AB); let res_correct: [u128; 9] = [0,0,0,0,0,0,16,0,0]; for i in 0..5 { assert!(easy_res[i] == res_correct[i]); } } #[test] fn to_montgomery_conversion() { let a = Scalar::to_montgomery(&A); for i in 0..5 { assert!(a[i] == A_MONT[i]); } } #[test] fn from_montgomery_conversion() { let y = Scalar::from_montgomery(&Y_MONT); for i in 0..5 { assert!(y[i] == Y[i]); } } #[test] fn scalar_mul() { let res = &X * &Y; for i in 0..5 { assert!(res[i] == X_TIMES_Y[i]); } } #[test] fn mul_by_identity() { let res = &Y * &Scalar::identity(); println!("{:?}", res); for i in 0..5 { assert!(res[i] == Y[i]); } } #[test] fn mul_by_zero() { let res = &Y * &Scalar::zero(); for i in 0..5 { assert!(res[i] == Scalar::zero()[i]); } } #[test] fn montgomery_mul() { let res = Scalar::montgomery_mul(&X, &Y); for i in 0..5 { assert!(res[i] == X_TIMES_Y_MONT[i]); } } #[test] fn square() { let res = &Y.square(); for i in 0..5 { assert!(res[i] == Y_SQ[i]); } } #[test] fn square_zero_and_identity() { let zero = &Scalar::zero().square(); let one = &Scalar::identity().square(); for i in 0..5 { assert!(zero[i] == Scalar::zero()[i]); assert!(one[i] == Scalar::one()[i]); } } #[test] fn half() { let res = &Y.half(); for i in 0..5 { assert!(res[i] == Y_HALF[i]); } let a_half = Scalar([0, 0, 0, 1, 0]); let a_half_half = Scalar([0, 0, 2251799813685248, 0, 0]); for i in 0..5 { assert!(a_half[i] == A.half()[i]); assert!(a_half_half[i] == A.half().half()[i]); } } #[test] fn even_scalar() { assert!(Y.is_even()); assert!(!X.is_even()); assert!(Scalar::zero().is_even()); } }
{ self.0[0].is_even() }
get_tag_by_product.py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'GetTagByProductResult', 'AwaitableGetTagByProductResult', 'get_tag_by_product', ] @pulumi.output_type class GetTagByProductResult: """ Tag Contract details. """ def __init__(__self__, display_name=None, id=None, name=None, type=None): if display_name and not isinstance(display_name, str): raise TypeError("Expected argument 'display_name' to be a str") pulumi.set(__self__, "display_name", display_name) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter(name="displayName") def display_name(self) -> str: """ Tag name. """ return pulumi.get(self, "display_name") @property @pulumi.getter def id(self) -> str: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter def type(self) -> str: """ Resource type for API Management resource. """ return pulumi.get(self, "type") class AwaitableGetTagByProductResult(GetTagByProductResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetTagByProductResult( display_name=self.display_name, id=self.id, name=self.name, type=self.type) def get_tag_by_product(product_id: Optional[str] = None, resource_group_name: Optional[str] = None, service_name: Optional[str] = None, tag_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTagByProductResult: """ Tag Contract details. :param str product_id: Product identifier. Must be unique in the current API Management service instance. :param str resource_group_name: The name of the resource group. :param str service_name: The name of the API Management service. :param str tag_id: Tag identifier. Must be unique in the current API Management service instance. """ __args__ = dict() __args__['productId'] = product_id __args__['resourceGroupName'] = resource_group_name __args__['serviceName'] = service_name __args__['tagId'] = tag_id if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:apimanagement/v20191201:getTagByProduct', __args__, opts=opts, typ=GetTagByProductResult).value return AwaitableGetTagByProductResult( display_name=__ret__.display_name, id=__ret__.id,
name=__ret__.name, type=__ret__.type)
samples.rs
use assert_cli; #[test] fn sample0()
#[test] fn sample1() { assert_cli::Assert::main_binary() .stdin( "R75,D30,R83,U83,L12,D49,R71,U7,L72 U62,R66,U55,R34,D71,R55,D58,R83", ) .stdout() .is("610") .unwrap(); } #[test] fn sample2() { assert_cli::Assert::main_binary() .stdin( "R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51 U98,R91,D20,R16,D67,R40,U7,R15,U6,R7", ) .stdout() .is("410") .unwrap(); } #[test] fn puzzle1() { assert_cli::Assert::main_binary() .stdin(include_str!("../data/puzzle1.in")) .stdout() .is("16524") .unwrap(); }
{ assert_cli::Assert::main_binary() .stdin( "R8,U5,L5,D3 U7,R6,D4,L4", ) .stdout() .is("30") .unwrap(); }
node_pool.go
package v1 import ( "fmt" "sort" "strconv" "strings" "github.com/mlab-lattice/lattice/pkg/api/v1" kubeutil "github.com/mlab-lattice/lattice/pkg/backend/kubernetes/util/kubernetes" "github.com/mlab-lattice/lattice/pkg/definition/tree" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var ( NodePoolKind = SchemeGroupVersion.WithKind("NodePool") NodePoolListKind = SchemeGroupVersion.WithKind("NodePoolList") NodePoolIDLabelKey = fmt.Sprintf("node-pool.%v/id", GroupName) // NodePoolServiceDedicatedID is the key for a label indicating that the node pool is dedicated for a service. // The label's value should be the ID of the service. // TODO: should we just use ServiceIDLabelKey here instead? if so what do we use for shared/lattice node pools NodePoolServiceDedicatedIDLabelKey = fmt.Sprintf("service.dedicated.node-pool.%v/id", GroupName) // NodePoolSystemSharedPathLabelKey is the key for a label indicating that the node pool is shared for a system. // The label's value should be the node pool's path in the system definition. NodePoolSystemSharedPathLabelKey = fmt.Sprintf("shared.node-pool.%v/path", GroupName) NodePoolSystemSharedNameLabelKey = fmt.Sprintf("shared.node-pool.%v/name", GroupName) // NodePoolWorkloadAnnotationKey is the key that should be used in an annotation by // workloads that run on a node pool. NodePoolWorkloadAnnotationKey = fmt.Sprintf("workload.%v/node-pools", GroupName) AllNodePoolsSelector = corev1.NodeSelector{ NodeSelectorTerms: []corev1.NodeSelectorTerm{ { MatchExpressions: []corev1.NodeSelectorRequirement{ { Key: NodePoolIDLabelKey, Operator: corev1.NodeSelectorOpExists, }, }, }, }, } AllNodePoolAffinity = corev1.NodeAffinity{ RequiredDuringSchedulingIgnoredDuringExecution: &AllNodePoolsSelector, } AllNodePoolToleration = corev1.Toleration{ Key: NodePoolIDLabelKey, Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoSchedule, } ) func NodePoolIDLabelInfo(namespacePrefix, value string) (v1.SystemID, string, NodePoolEpoch, error) { parts := strings.Split(value, ".") if len(parts) != 3 { return "", "", 0, fmt.Errorf("malformed node pool ID label") } systemID, err := kubeutil.SystemID(namespacePrefix, parts[0]) if err != nil { return "", "", 0, err } nodePoolID := parts[1] epochStr := parts[2] epoch, err := strconv.ParseInt(epochStr, 10, 64) if err != nil { return "", "", 0, fmt.Errorf("error converting epoch string value %v: %v", epochStr, err) } return systemID, nodePoolID, NodePoolEpoch(epoch), nil } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type NodePool struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata"` Spec NodePoolSpec `json:"spec"` Status NodePoolStatus `json:"status,omitempty"` } func (np *NodePool) ID(epoch NodePoolEpoch) string { return fmt.Sprintf("%v.%v.%v", np.Namespace, np.Name, epoch) } type NodePoolType string const ( NodePoolTypeServiceDedicated NodePoolType = "service-dedicated" NodePoolTypeSystemShared NodePoolType = "system-shared" ) func (np *NodePool) ServiceDedicatedIDLabel() (string, bool) { serviceID, ok := np.Labels[NodePoolServiceDedicatedIDLabelKey] return serviceID, ok } func (np *NodePool) SystemSharedPathLabel() (tree.PathSubcomponent, bool, error) { pathLabel, ok := np.Labels[NodePoolSystemSharedPathLabelKey] if !ok { return "", false, nil } nameLabel, ok := np.Labels[NodePoolSystemSharedNameLabelKey] if !ok { return "", false, nil } path, err := tree.NewPathFromDomain(pathLabel) if err != nil { return "", false, err } subcomponent, err := tree.NewPathSubcomponentFromParts(path, nameLabel) if err != nil { return "", false, err } return subcomponent, true, nil } func (np *NodePool) TypeDescription() string { if np.Labels == nil { return "UNKNOWN" } if serviceID, ok := np.ServiceDedicatedIDLabel(); ok { return fmt.Sprintf("dedicated for service %v", serviceID) } if path, ok, err := np.SystemSharedPathLabel(); err == nil && ok { return fmt.Sprintf("shared node pool %v", path) } return "UNKNOWN" } func (np *NodePool) Description(namespacePrefix string) string { // TODO: when adding lattice node pools may have to adjust this systemID, err := kubeutil.SystemID(namespacePrefix, np.Namespace) if err != nil { systemID = v1.SystemID(fmt.Sprintf("UNKNOWN (namespace: %v)", np.Namespace)) } return fmt.Sprintf("node pool %v (%v in system %v)", np.Name, np.TypeDescription(), systemID) } func (np *NodePool) Stable() bool { return np.UpdateProcessed() && np.Status.State == NodePoolStateStable } func (np *NodePool) Failed() bool { return np.UpdateProcessed() && np.Status.State == NodePoolStateFailed } func (np *NodePool) UpdateProcessed() bool { return np.Status.ObservedGeneration >= np.Generation } func (np *NodePool) Reason() string { if !np.UpdateProcessed() { return "waiting for update to be processed" } switch np.Status.State { case NodePoolStateStable: return "" case NodePoolStateUpdating: return "updating" case NodePoolStatePending: return "pending" case NodePoolStateScaling: return "scaling" case NodePoolStateDeleting: return "deleting" case NodePoolStateFailed: failureReason := "unknown reason" if np.Status.FailureInfo != nil { failureReason = fmt.Sprintf( "%v at %v", np.Status.FailureInfo.Message, np.Status.FailureInfo.Timestamp.String(), ) } return fmt.Sprintf("failed: %v", failureReason) default: return fmt.Sprintf("in unknown state: %v", np.Status.State) } } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type NodePoolEpoch int64 func (np *NodePool) Affinity(epoch NodePoolEpoch) *corev1.NodeAffinity { return &corev1.NodeAffinity{ RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{ NodeSelectorTerms: []corev1.NodeSelectorTerm{ { MatchExpressions: []corev1.NodeSelectorRequirement{ { Key: NodePoolIDLabelKey, Operator: corev1.NodeSelectorOpIn, Values: []string{np.ID(epoch)}, }, }, }, }, }, } } func (np *NodePool) Toleration(epoch NodePoolEpoch) corev1.Toleration { return corev1.Toleration{ Key: NodePoolIDLabelKey, Operator: corev1.TolerationOpEqual, Value: np.ID(epoch), Effect: corev1.TaintEffectNoSchedule, } } type NodePoolSpec struct { NumInstances int32 `json:"numInstances"` InstanceType string `json:"instanceType"` } type NodePoolStatus struct { ObservedGeneration int64 `json:"observedGeneration"` State NodePoolState `json:"state"` FailureInfo *NodePoolStatusFailureInfo `json:"failureInfo"` // Epochs is a mapping from an epoch to the status of that epoch. // An epoch is a manifestation of the node pool that requires replacing infrastructure. // For example, changing the instance type of a node pool will require new nodes, // and thus requires a new epoch of the node pool. // Changing the number of nodes in a node pool does not require replacing the // existing nodes, simply scaling them, and thus does not require a new epoch. Epochs NodePoolStatusEpochs `json:"epochs"` } type NodePoolStatusFailureInfo struct { Message string `json:"message"` Timestamp metav1.Time `json:"time"` } type NodePoolStatusEpochs map[NodePoolEpoch]NodePoolStatusEpoch func (e NodePoolStatusEpochs) Epochs() []NodePoolEpoch { var epochs []NodePoolEpoch for epoch := range e { epochs = append(epochs, epoch) } sort.Slice(epochs, func(i, j int) bool { return epochs[i] < epochs[j] }) return epochs } func (e NodePoolStatusEpochs) CurrentEpoch() (NodePoolEpoch, bool) { epochs := e.Epochs() if len(epochs) == 0 { return 0, false } return epochs[len(epochs)-1], true } func (e NodePoolStatusEpochs) NextEpoch() NodePoolEpoch { current, ok := e.CurrentEpoch() if !ok { return 1 } return current + 1 } func (e NodePoolStatusEpochs) Epoch(epoch NodePoolEpoch) (*NodePoolStatusEpoch, bool) { status, ok := e[epoch] if !ok { return nil, false } return &status, true } type NodePoolState string const ( NodePoolStatePending NodePoolState = "" NodePoolStateScaling NodePoolState = "scaling" NodePoolStateUpdating NodePoolState = "updating" NodePoolStateStable NodePoolState = "stable" NodePoolStateFailed NodePoolState = "failed" NodePoolStateDeleting NodePoolState = "deleting" ) type NodePoolStatusEpoch struct { Spec NodePoolSpec `json:"spec"` Status NodePoolStatusEpochStatus `json:"status"` } type NodePoolStatusEpochStatus struct { NumInstances int32 `json:"numInstances"` InstanceType string `json:"instanceType"` State NodePoolState `json:"state"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type NodePoolList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []NodePool `json:"items"` } // NodePoolAnnotation is the type that should be the value of the NodePoolWorkloadAnnotationKey annotation. // It maps from namespaces to a map of names to a slice of epochs. // For example, if a service is currently running on the abc node pool in namespace bar, and is // on both epochs 1 and 2 of that node pool, and is also currently running on the xyz node pool // in namespace foo, and is running on epoch 5 of that node pool, the annotation should have // the following value: // { // "bar": { "abc": [1, 2] }, // "foo": { "xyz": [5] } // } type NodePoolAnnotationValue map[string]NodePoolAnnotationValueNamespace func (in NodePoolAnnotationValue) DeepCopyInto(out *NodePoolAnnotationValue) { { in := &in *out = make(NodePoolAnnotationValue, len(*in)) for key, val := range *in { // generated deep copy kept trying to dereference the result of val.DeepCopy(), // but in this case it's not a pointer so it shouldn't be dereferenced (*out)[key] = val.DeepCopy() } return } } type NodePoolAnnotationValueNamespace map[string][]NodePoolEpoch func (a NodePoolAnnotationValue) IsEmpty() bool { return len(a) == 0 } func (a NodePoolAnnotationValue) NodePools(namespace string) (map[string][]NodePoolEpoch, bool) { nodePools, ok := a[namespace] return nodePools, ok } func (a NodePoolAnnotationValue) Add(namespace, nodePool string, epoch NodePoolEpoch) { nodePools, ok := a.NodePools(namespace) if !ok { nodePools = make(map[string][]NodePoolEpoch) } epochs, ok := nodePools[nodePool] if !ok { epochs = make([]NodePoolEpoch, 0) } containsEpoch := false for _, e := range epochs { if e == epoch { containsEpoch = true break } } if !containsEpoch { epochs = append(epochs, epoch) } sort.Slice(epochs, func(i, j int) bool { return epochs[i] < epochs[j] }) nodePools[nodePool] = epochs a[namespace] = nodePools } func (a NodePoolAnnotationValue) Epochs(namespace, nodePool string) ([]NodePoolEpoch, bool) { nodePools, ok := a.NodePools(namespace) if !ok { return nil, false } epochs, ok := nodePools[nodePool] return epochs, ok } func (a NodePoolAnnotationValue) ContainsNodePool(namespace, nodePool string) bool { _, ok := a.Epochs(namespace, nodePool) return ok } func (a NodePoolAnnotationValue) ContainsLargerEpoch(namespace, nodePool string, epoch NodePoolEpoch) bool { epochs, ok := a.Epochs(namespace, nodePool) if !ok { return false } for _, e := range epochs { if e > epoch {
} } return false } func (a NodePoolAnnotationValue) ContainsEpoch(namespace, nodePool string, epoch NodePoolEpoch) bool { epochs, ok := a.Epochs(namespace, nodePool) if !ok { return false } for _, e := range epochs { if e == epoch { return true } } return false }
return true
bls12_377.rs
use crate::field::*; use crate::fp::*; use crate::extension_towers::fp2::*; use crate::extension_towers::fp6_as_3_over_2::*; use crate::extension_towers::fp12_as_2_over3_over_2::*; use crate::weierstrass::*; use crate::weierstrass::curve::*; use crate::pairings::bls12::*; use crate::pairings::TwistType; use crate::integers::MaxFieldUint; const REPR_ZERO: U384Repr = U384Repr([0,0,0,0,0,0]); pub const BLS12_377_MODULUS_UINT: MaxFieldUint = MaxFieldUint::from_limbs( [ 0x8508c00000000001,0x170b5d4430000000,0x1ef3622fba094800,0x1a22d9f300f5138f, 0xc63b05c06ca1493b,0x01ae3a4617c510ea, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 ] ); pub const BLS12_377_MODULUS: U384Repr = U384Repr([0x8508c00000000001,0x170b5d4430000000,0x1ef3622fba094800,0x1a22d9f300f5138f,0xc63b05c06ca1493b,0x01ae3a4617c510ea]); const BLS12_377_R: U384Repr = U384Repr([0x02cdffffffffff68,0x51409f837fffffb1,0x9f7db3a98a7d3ff2,0x7b4e97b76e7c6305,0x4cf495bf803c84e8,0x008d6661e2fdf49a]); const BLS12_377_R2: U384Repr = U384Repr([0xb786686c9400cd22,0x0329fcaab00431b1,0x22a5f11162d6b46d,0xbfdf7d03827dc3ac,0x837e92f041790bf9,0x006dfccb1e914b88]); const BLS12_377_MONT_INV: u64 = 0x8508bfffffffffff; pub const BLS12_377_FIELD: PrimeField<U384Repr> = PrimeField::<U384Repr> { mont_power: 384, modulus_bits: 377, modulus: BLS12_377_MODULUS, mont_r: BLS12_377_R, mont_r2: BLS12_377_R2, mont_inv: BLS12_377_MONT_INV, }; const BLS12_377_FP_NON_RESIDUE_REPR: U384Repr = U384Repr([0xfc0b8000000002fa,0x97d39cf6e000018b,0x2072420fbfa05044,0xcbbcbd50d97c3802,0x0baf1ec35813f9eb,0x009974a2c0945ad2]); const BLS12_377_FP_NON_RESIDUE: decl_fp!(U384Repr) = repr_into_fp!( BLS12_377_FP_NON_RESIDUE_REPR, U384Repr, BLS12_377_FIELD ); pub const BLS12_377_FP_ZERO: decl_fp!(U384Repr) = repr_into_fp!( REPR_ZERO, U384Repr, BLS12_377_FIELD ); pub const BLS12_377_FP_ONE: decl_fp!(U384Repr) = repr_into_fp!( BLS12_377_R, U384Repr, BLS12_377_FIELD ); const BLS12_377_EXTENSION_2_FROB_COEFF_0_REPR: U384Repr = U384Repr([0x02cdffffffffff68,0x51409f837fffffb1,0x9f7db3a98a7d3ff2,0x7b4e97b76e7c6305,0x4cf495bf803c84e8,0x008d6661e2fdf49a]); const BLS12_377_EXTENSION_2_FROB_COEFF_1_REPR: U384Repr = U384Repr([0x823ac00000000099,0xc5cabdc0b000004f,0x7f75ae862f8c080d,0x9ed4423b9278b089,0x79467000ec64c452,0x0120d3e434c71c50]); const BLS12_377_EXTENSION_2_FROB_COEFF_0: decl_fp!(U384Repr) = repr_into_fp!( BLS12_377_EXTENSION_2_FROB_COEFF_0_REPR, U384Repr, BLS12_377_FIELD ); const BLS12_377_EXTENSION_2_FROB_COEFF_1: decl_fp!(U384Repr) = repr_into_fp!( BLS12_377_EXTENSION_2_FROB_COEFF_1_REPR, U384Repr, BLS12_377_FIELD ); pub const BLS12_377_EXTENSION_2_FIELD: Extension2<'static, U384Repr, PrimeField<U384Repr>> = Extension2::<'static, U384Repr, PrimeField<U384Repr>> { field: &BLS12_377_FIELD, non_residue: BLS12_377_FP_NON_RESIDUE, frobenius_coeffs_c1: [BLS12_377_EXTENSION_2_FROB_COEFF_0, BLS12_377_EXTENSION_2_FROB_COEFF_1], frobenius_coeffs_are_calculated: true }; const BLS12_377_FP2_NON_RESIDUE_C0_REPR: U384Repr = U384Repr([0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000]); const BLS12_377_FP2_NON_RESIDUE_C1_REPR: U384Repr = U384Repr([0x02cdffffffffff68,0x51409f837fffffb1,0x9f7db3a98a7d3ff2,0x7b4e97b76e7c6305,0x4cf495bf803c84e8,0x008d6661e2fdf49a]); const BLS12_377_FP2_NON_RESIDUE_C0: decl_fp!(U384Repr) = repr_into_fp!( BLS12_377_FP2_NON_RESIDUE_C1_REPR, U384Repr, BLS12_377_FIELD ); const BLS12_377_FP2_NON_RESIDUE_C1: decl_fp!(U384Repr) = repr_into_fp!( BLS12_377_FP2_NON_RESIDUE_C1_REPR, U384Repr, BLS12_377_FIELD ); const BLS12_377_FP2_NON_RESIDUE: decl_fp2!(U384Repr) = repr_into_fp2!( BLS12_377_FP2_NON_RESIDUE_C0, BLS12_377_FP2_NON_RESIDUE_C1, U384Repr, BLS12_377_EXTENSION_2_FIELD ); pub const BLS12_377_SUBGROUP_ORDER: [u64; 4] = [ 0x0a11800000000001, 0x59aa76fed0000001, 0x60b44d1e5c37b001, 0x12ab655e9a2ca556 ]; const BLS12_377_X: [u64; 1] = [0x8508c00000000001]; const BLS12_377_X_IS_NEGATIVE: bool = false; const BLS12_377_B_FOR_G1_REPR: U384Repr = U384Repr([0x862f3ffffffffd9f,0x2df720c9cffffec3,0x5f036c766febb7c9,0xd31784eab8fc7887,0x6d97513d9450ca66,0x00875f417432c17e]); const BLS12_377_B_FOR_G1: Fp<'static, U384Repr, PrimeField<U384Repr>> = Fp::<'static, U384Repr, PrimeField<U384Repr>> { field: &BLS12_377_FIELD, repr: BLS12_377_B_FOR_G1_REPR }; const BLS12_377_B_FOR_G2_C0_REPR: U384Repr = U384Repr([0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000]); const BLS12_377_B_FOR_G2_C1_REPR: U384Repr = U384Repr([0x01c8999999999a14,0x37d5649a266666a6,0xff91586b593cd33e,0xe5769b62db93c06d,0x2dd1f333f0509d0e,0x00e70fe9c3d27d0d]); const BLS12_377_B_FOR_G2_C0: Fp<'static, U384Repr, PrimeField<U384Repr>> = Fp::<'static, U384Repr, PrimeField<U384Repr>> { field: &BLS12_377_FIELD, repr: BLS12_377_B_FOR_G2_C0_REPR }; const BLS12_377_B_FOR_G2_C1: Fp<'static, U384Repr, PrimeField<U384Repr>> = Fp::<'static, U384Repr, PrimeField<U384Repr>> { field: &BLS12_377_FIELD, repr: BLS12_377_B_FOR_G2_C1_REPR }; const BLS12_377_B_FOR_G2: Fp2<'static, U384Repr, PrimeField<U384Repr>> = Fp2::<'static, U384Repr, PrimeField<U384Repr>> { c0: BLS12_377_B_FOR_G2_C0, c1: BLS12_377_B_FOR_G2_C1, extension_field: &BLS12_377_EXTENSION_2_FIELD }; pub const BLS12_377_G1_CURVE_PARAMETERS: CurveOverFpParameters<'static, U384Repr, PrimeField<U384Repr>> = CurveOverFpParameters::<'static, U384Repr, PrimeField<U384Repr>> { field: &BLS12_377_FIELD }; pub const BLS12_377_G2_CURVE_PARAMETERS: CurveOverFp2Parameters<'static, U384Repr, PrimeField<U384Repr>> = CurveOverFp2Parameters::<'static, U384Repr, PrimeField<U384Repr>> { field: &BLS12_377_EXTENSION_2_FIELD }; pub const BLS12_377_FP2_ZERO: decl_fp2!(U384Repr) = repr_into_fp2!( BLS12_377_FP_ZERO, BLS12_377_FP_ZERO, U384Repr, BLS12_377_EXTENSION_2_FIELD ); pub const BLS12_377_FP2_ONE: decl_fp2!(U384Repr) = repr_into_fp2!( BLS12_377_FP_ONE, BLS12_377_FP_ZERO, U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP6_FROB_C1_0: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x02cdffffffffff68,0x51409f837fffffb1,0x9f7db3a98a7d3ff2,0x7b4e97b76e7c6305,0x4cf495bf803c84e8,0x008d6661e2fdf49a]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP6_FROB_C1_1: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x1dab52f567cdf753,0x275ba68225d3fcbf,0xd479033c31671c95,0xbaf5e01f45f5eeb2,0xc124ac0d60ff519a,0x012e21e26d3f27d6]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0xe8175168f936f1a3,0xa1f9faad6e240880,0x0327ea0da32ce732,0xcbc495c1e2fe7cc2,0xbef5b5eec7980fde,0x00450861e49e5fb2]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP6_FROB_C1_2: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x2c766f925a7b8727,0x03d7f6b0253d58b5,0x838ec0deec122131,0xbd5eb3e9f658bb10,0x6942bd126ed3e52e,0x01673786dd04ed6a]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP6_FROB_C1_3: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0xe4a79fc4d4b5361f,0x3f77620e95796e81,0xc331b835dbe63ed4,0x7d9226378f678321,0xe8d237560a8dc3e4,0x008a6a848e739d69]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0xa03b8e62d0fd012f,0x93c031ea435b3d76,0xafc6f5dbe5871aef,0x7cc296b19f5040e7,0xcd2bc9301cdc60ac,0x01310f7ced1c32b7]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP6_FROB_C1_4: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP6_FROB_C1_5: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP6_FROB_C2_0: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x02cdffffffffff68,0x51409f837fffffb1,0x9f7db3a98a7d3ff2,0x7b4e97b76e7c6305,0x4cf495bf803c84e8,0x008d6661e2fdf49a]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP6_FROB_C2_1: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x88b5c17a7958b2fe,0x7f5e7e57ba07bc1c,0x6610c4919f5335d4,0x2662d66110d01894,0x528db91fde4912ee,0x01578d053afcb64e]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x7ce7510b8d5e6d45,0x0623598c82c4f51b,0xc595749a3ca4dfb7,0x4089827645e7035a,0x1d4fa3a2051729e1,0x0028dcfa7aab9072]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP6_FROB_C2_2: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0xdacd106da5847973,0xd8fe2454bac2a79a,0x1ada4fd6fd832edc,0xfb9868449d150908,0xd63eb8aeea32285e,0x0167d6a36f873fd0]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP6_FROB_C2_3: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x6693d2d815e1849f,0xb8317b4d8c16fa8f,0x417a052262ed3938,0xbb4a9f4398ca0e30,0xf0a0eca1f774c413,0x0103be639ab8b9b1]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x1e9a7f00446c4415,0xa2adab41fb145979,0x8974112b4fb7fd03,0x7ea657b93a6854e4,0xe5d71e58ba63a9d1,0x009d3c2719419801]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP6_FROB_C2_4: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP6_FROB_C2_5: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; pub const BLS12_377_EXTENSION_6_FIELD: Extension3Over2<'static, U384Repr, PrimeField<U384Repr>> = Extension3Over2::<'static, U384Repr, PrimeField<U384Repr>> { non_residue: BLS12_377_FP2_NON_RESIDUE, field: &BLS12_377_EXTENSION_2_FIELD, frobenius_coeffs_c1: [BLS12_377_FP6_FROB_C1_0, BLS12_377_FP6_FROB_C1_1, BLS12_377_FP6_FROB_C1_2, BLS12_377_FP6_FROB_C1_3, BLS12_377_FP6_FROB_C1_4, BLS12_377_FP6_FROB_C1_5], frobenius_coeffs_c2: [BLS12_377_FP6_FROB_C2_0, BLS12_377_FP6_FROB_C2_1, BLS12_377_FP6_FROB_C2_2, BLS12_377_FP6_FROB_C2_3, BLS12_377_FP6_FROB_C2_4, BLS12_377_FP6_FROB_C2_5], frobenius_coeffs_are_calculated: true }; const BLS12_377_FP12_FROB_C1_0: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x02cdffffffffff68,0x51409f837fffffb1,0x9f7db3a98a7d3ff2,0x7b4e97b76e7c6305,0x4cf495bf803c84e8,0x008d6661e2fdf49a]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP12_FROB_C1_1: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x8e4881eda9715337,0x68933c1b14707f81,0xabe52b0749129354,0x039d6a8fb0acdc2e,0x77c4c0656b2dc79b,0x0102a8dbf4497b6a]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0xfe29bc6ac0baf987,0xcbd4ec5004bfc592,0x12f93242a0ff802b,0x6fbab242c943d0fe,0x0362fa6af0205e6e,0x013a4205b11a7684]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP12_FROB_C1_2: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0xdacd106da5847973,0xd8fe2454bac2a79a,0x1ada4fd6fd832edc,0xfb9868449d150908,0xd63eb8aeea32285e,0x0167d6a36f873fd0]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP12_FROB_C1_3: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0xc059cd145fe9bd8c,0xdb5711d0ca9b5c20,0xff5b91f6ceecf992,0x2c9e02f131e3fecb,0x6b1d1c9c56f21cd0,0x019d034f7fdacf4e]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0xe5bf2331ea1a4ad9,0xfa109dcb130047d8,0x5322840482579c81,0xe07b400cda4647b3,0xcdbfbc15d4645c07,0x008f9a1e7e02e793]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP12_FROB_C1_4: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP12_FROB_C1_5: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP12_FROB_C1_6: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x02cdffffffffff68,0x51409f837fffffb1,0x9f7db3a98a7d3ff2,0x7b4e97b76e7c6305,0x4cf495bf803c84e8,0x008d6661e2fdf49a]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000,0x0000000000000000]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_FP12_FROB_C1_7: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP12_FROB_C1_8: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP12_FROB_C1_9: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP12_FROB_C1_10: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP12_FROB_C1_11: decl_fp2!(U384Repr) = BLS12_377_FP2_ZERO; const BLS12_377_FP6_ZERO: Fp6<'static, U384Repr, PrimeField<U384Repr>> = Fp6::<'static, U384Repr, PrimeField<U384Repr>> { c0: BLS12_377_FP2_ZERO, c1: BLS12_377_FP2_ZERO, c2: BLS12_377_FP2_ZERO, extension_field: &BLS12_377_EXTENSION_6_FIELD }; pub const BLS12_377_EXTENSION_12_FIELD: Extension2Over3Over2<'static, U384Repr, PrimeField<U384Repr>> = Extension2Over3Over2::<'static, U384Repr, PrimeField<U384Repr>> { non_residue: BLS12_377_FP6_ZERO, field: &BLS12_377_EXTENSION_6_FIELD, frobenius_coeffs_c1: [ BLS12_377_FP12_FROB_C1_0, BLS12_377_FP12_FROB_C1_1, BLS12_377_FP12_FROB_C1_2, BLS12_377_FP12_FROB_C1_3, BLS12_377_FP12_FROB_C1_4, BLS12_377_FP12_FROB_C1_5, BLS12_377_FP12_FROB_C1_6, BLS12_377_FP12_FROB_C1_7, BLS12_377_FP12_FROB_C1_8, BLS12_377_FP12_FROB_C1_9, BLS12_377_FP12_FROB_C1_10, BLS12_377_FP12_FROB_C1_11 ], frobenius_coeffs_are_calculated: true }; pub const BLS12_377_G1_CURVE: WeierstrassCurve<'static, CurveOverFpParameters<'static, U384Repr, PrimeField<U384Repr>>> = WeierstrassCurve::<'static, CurveOverFpParameters<'static, U384Repr, PrimeField<U384Repr>>> { a: BLS12_377_FP_ZERO, b: BLS12_377_B_FOR_G1, curve_type: CurveType::AIsZero, subgroup_order_repr: &BLS12_377_SUBGROUP_ORDER, params: &BLS12_377_G1_CURVE_PARAMETERS }; pub const BLS12_377_G2_CURVE: WeierstrassCurve<'static, CurveOverFp2Parameters<'static, U384Repr, PrimeField<U384Repr>>> = WeierstrassCurve::<'static, CurveOverFp2Parameters<'static, U384Repr, PrimeField<U384Repr>>> { a: BLS12_377_FP2_ZERO, b: BLS12_377_B_FOR_G2, curve_type: CurveType::AIsZero, subgroup_order_repr: &BLS12_377_SUBGROUP_ORDER, params: &BLS12_377_G2_CURVE_PARAMETERS }; const BLS12_377_G1_GENERATOR_X: decl_fp!(U384Repr) = repr_into_fp!( U384Repr([0x260f33b9772451f4,0xc54dd773169d5658,0x5c1551c469a510dd,0x761662e4425e1698,0xc97d78cc6f065272,0x00a41206b361fd4d]), U384Repr, BLS12_377_FIELD ); const BLS12_377_G1_GENERATOR_Y: decl_fp!(U384Repr) = repr_into_fp!( U384Repr([0x8193961fb8cb81f3,0x00638d4c5f44adb8,0xfafaf3dad4daf54a,0xc27849e2d655cd18,0x2ec3ddb401d52814,0x007da93326303c71]), U384Repr, BLS12_377_FIELD ); const BLS12_377_G2_GENERATOR_X: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0x68904082f268725b,0x668f2ea74f45328b,0xebca7a65802be84f,0x1e1850f4c1ada3e6,0x830dc22d588ef1e9,0x01862a81767c0982]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x5f02a915c91c7f39,0xf8c553ba388da2a7,0xd51a416dbd198850,0xe943c6f38ae3073a,0xffe24aa8259a4981,0x011853391e73dfdd]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); const BLS12_377_G2_GENERATOR_Y: decl_fp2!(U384Repr) = repr_into_fp2!( repr_into_fp!( U384Repr([0xd5b19b897881430f,0x05be9118a5b371ed,0x6063f91f86c131ee,0x3244a61be8f4ec19,0xa02e425b9f9a3a12,0x018af8c04f3360d2]), U384Repr, BLS12_377_FIELD ), repr_into_fp!( U384Repr([0x57601ac71a5b96f5,0xe99acc1714f2440e,0x2339612f10118ea9,0x8321e68a3b1cd722,0x2b543b050cc74917,0x00590182b396c112]), U384Repr, BLS12_377_FIELD ), U384Repr, BLS12_377_EXTENSION_2_FIELD ); pub const BLS12_377_G1_GENERATOR: CurvePoint<'static, CurveOverFpParameters<'static, U384Repr, PrimeField<U384Repr>>> = CurvePoint::<'static, CurveOverFpParameters<'static, U384Repr, PrimeField<U384Repr>>> { curve: &BLS12_377_G1_CURVE, x: BLS12_377_G1_GENERATOR_X, y: BLS12_377_G1_GENERATOR_Y, z: BLS12_377_FP_ONE, }; pub const BLS12_377_G2_GENERATOR: CurvePoint<'static, CurveOverFp2Parameters<'static, U384Repr, PrimeField<U384Repr>>> = CurvePoint::<'static, CurveOverFp2Parameters<'static, U384Repr, PrimeField<U384Repr>>> { curve: &BLS12_377_G2_CURVE, x: BLS12_377_G2_GENERATOR_X, y: BLS12_377_G2_GENERATOR_Y, z: BLS12_377_FP2_ONE, }; pub const BLS12_377_PAIRING_ENGINE: Bls12Instance< 'static, U384Repr, PrimeField<U384Repr>, CurveOverFpParameters<'static, U384Repr, PrimeField<U384Repr>>, CurveOverFp2Parameters<'static, U384Repr, PrimeField<U384Repr>> > = Bls12Instance::< 'static, U384Repr, PrimeField<U384Repr>, CurveOverFpParameters<'static, U384Repr, PrimeField<U384Repr>>, CurveOverFp2Parameters<'static, U384Repr, PrimeField<U384Repr>> > { x: &BLS12_377_X, x_is_negative: BLS12_377_X_IS_NEGATIVE, twist_type: TwistType::D, base_field: &BLS12_377_FIELD, curve: &BLS12_377_G1_CURVE, curve_twist: &BLS12_377_G2_CURVE, fp2_extension: &BLS12_377_EXTENSION_2_FIELD, fp6_extension: &BLS12_377_EXTENSION_6_FIELD, fp12_extension: &BLS12_377_EXTENSION_12_FIELD, prefer_naf: false, x_naf: Vec::new() }; #[cfg(test)] mod test { use crate::traits::FieldElement; use super::*; use crate::public_interface::decode_g1::serialize_g1_point; #[test] fn test_engine_bilinearity() { use crate::weierstrass::Group; use crate::pairings::PairingEngine; let p = BLS12_377_G1_GENERATOR.clone(); let q = BLS12_377_G2_GENERATOR.clone(); let mut p2 = p.mul(vec![12345678]); p2.normalize(); let mut q2 = q.mul(vec![12345678]); q2.normalize(); let ans1 = BLS12_377_PAIRING_ENGINE.pair(&[p.clone()], &[q2]).unwrap(); let ans2 = BLS12_377_PAIRING_ENGINE.pair(&[p2], &[q.clone()]).unwrap(); let ans3 = BLS12_377_PAIRING_ENGINE.pair(&[p], &[q]).unwrap(); let ans3 = ans3.pow(&vec![12345678]); assert!(ans1 == ans2); assert!(ans1 == ans3); } fn output_test_vector(input: &[u8], output: &[u8])
fn serialize_scalar(repr: &[u64], len: usize) -> Vec<u8> { let a = MaxFieldUint::from(repr); let mut res = vec![0u8; a.as_ref().len() * 8]; a.to_big_endian(&mut res); res.reverse(); res.truncate(len); res.reverse(); res } #[test] fn test_g1_mul_by_zero() { let mut input_encoding = serialize_g1_point(48, &BLS12_377_G1_GENERATOR).expect("must serialize a generator"); let scalar = [0u64]; let scalar_encoding = serialize_scalar(&scalar, 32); input_encoding.extend(scalar_encoding); let mut out = BLS12_377_G1_GENERATOR.mul(&scalar); out.normalize(); let output_encoding = serialize_g1_point(48, &out).expect("must serialize a generator"); output_test_vector(&input_encoding, &output_encoding); } }
{ println!("Input: 0x{}", hex::encode(input)); println!("Output: 0x{}", hex::encode(output)); }
operations.rs
#![doc = "generated by AutoRust"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::models; #[derive(Clone)] pub struct Client { endpoint: String, credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, scopes: Vec<String>, pipeline: azure_core::Pipeline, } #[derive(Clone)] pub struct ClientBuilder { credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, endpoint: Option<String>, scopes: Option<Vec<String>>, } pub const DEFAULT_ENDPOINT: &str = azure_core::resource_manager_endpoint::AZURE_PUBLIC_CLOUD; impl ClientBuilder { pub fn new(credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>) -> Self { Self { credential, endpoint: None, scopes: None, } } pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self { self.endpoint = Some(endpoint.into()); self } pub fn scopes(mut self, scopes: &[&str]) -> Self { self.scopes = Some(scopes.iter().map(|scope| (*scope).to_owned()).collect()); self } pub fn build(self) -> Client { let endpoint = self.endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned()); let scopes = self.scopes.unwrap_or_else(|| vec![format!("{}/", endpoint)]); Client::new(endpoint, self.credential, scopes) } } impl Client { pub(crate) fn endpoint(&self) -> &str { self.endpoint.as_str() } pub(crate) fn token_credential(&self) -> &dyn azure_core::auth::TokenCredential { self.credential.as_ref() } pub(crate) fn scopes(&self) -> Vec<&str> { self.scopes.iter().map(String::as_str).collect() } pub(crate) async fn send(&self, request: impl Into<azure_core::Request>) -> azure_core::error::Result<azure_core::Response> { let mut context = azure_core::Context::default(); let mut request = request.into(); self.pipeline.send(&mut context, &mut request).await } pub fn new( endpoint: impl Into<String>, credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, scopes: Vec<String>, ) -> Self { let endpoint = endpoint.into(); let pipeline = azure_core::Pipeline::new( option_env!("CARGO_PKG_NAME"), option_env!("CARGO_PKG_VERSION"), azure_core::ClientOptions::default(), Vec::new(), Vec::new(), ); Self { endpoint, credential, scopes, pipeline, } } pub fn scheduled_query_rules(&self) -> scheduled_query_rules::Client { scheduled_query_rules::Client(self.clone()) } } #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] ScheduledQueryRules_ListBySubscription(#[from] scheduled_query_rules::list_by_subscription::Error), #[error(transparent)] ScheduledQueryRules_ListByResourceGroup(#[from] scheduled_query_rules::list_by_resource_group::Error), #[error(transparent)] ScheduledQueryRules_Get(#[from] scheduled_query_rules::get::Error), #[error(transparent)] ScheduledQueryRules_CreateOrUpdate(#[from] scheduled_query_rules::create_or_update::Error), #[error(transparent)] ScheduledQueryRules_Update(#[from] scheduled_query_rules::update::Error), #[error(transparent)] ScheduledQueryRules_Delete(#[from] scheduled_query_rules::delete::Error), } pub mod scheduled_query_rules { use super::models; pub struct Client(pub(crate) super::Client); impl Client { pub fn list_by_subscription(&self, subscription_id: impl Into<String>) -> list_by_subscription::Builder { list_by_subscription::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), } } pub fn list_by_resource_group( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, ) -> list_by_resource_group::Builder
pub fn get( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, rule_name: impl Into<String>, ) -> get::Builder { get::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), rule_name: rule_name.into(), } } pub fn create_or_update( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, rule_name: impl Into<String>, parameters: impl Into<models::ScheduledQueryRuleResource>, ) -> create_or_update::Builder { create_or_update::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), rule_name: rule_name.into(), parameters: parameters.into(), } } pub fn update( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, rule_name: impl Into<String>, parameters: impl Into<models::ScheduledQueryRuleResourcePatch>, ) -> update::Builder { update::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), rule_name: rule_name.into(), parameters: parameters.into(), } } pub fn delete( &self, subscription_id: impl Into<String>, resource_group_name: impl Into<String>, rule_name: impl Into<String>, ) -> delete::Builder { delete::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), rule_name: rule_name.into(), } } } pub mod list_by_subscription { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorContract, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, } impl Builder { pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::ScheduledQueryRuleResourceCollection, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Insights/scheduledQueryRules", self.client.endpoint(), &self.subscription_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2021-08-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ScheduledQueryRuleResourceCollection = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorContract = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod list_by_resource_group { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorContract, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, } impl Builder { pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::ScheduledQueryRuleResourceCollection, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Insights/scheduledQueryRules", self.client.endpoint(), &self.subscription_id, &self.resource_group_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2021-08-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ScheduledQueryRuleResourceCollection = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorContract = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorContract, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) rule_name: String, } impl Builder { pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::ScheduledQueryRuleResource, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Insights/scheduledQueryRules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.rule_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2021-08-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ScheduledQueryRuleResource = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorContract = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod create_or_update { use super::models; #[derive(Debug)] pub enum Response { Ok200(models::ScheduledQueryRuleResource), Created201(models::ScheduledQueryRuleResource), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorContract, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) rule_name: String, pub(crate) parameters: models::ScheduledQueryRuleResource, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Insights/scheduledQueryRules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.rule_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2021-08-01"); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ScheduledQueryRuleResource = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ScheduledQueryRuleResource = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(Response::Created201(rsp_value)) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorContract = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod update { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorContract, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) rule_name: String, pub(crate) parameters: models::ScheduledQueryRuleResourcePatch, } impl Builder { pub fn into_future( self, ) -> futures::future::BoxFuture<'static, std::result::Result<models::ScheduledQueryRuleResource, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Insights/scheduledQueryRules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.rule_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2021-08-01"); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.parameters).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ScheduledQueryRuleResource = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorContract = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod delete { use super::models; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorContract, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) subscription_id: String, pub(crate) resource_group_name: String, pub(crate) rule_name: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> { Box::pin(async move { let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Insights/scheduledQueryRules/{}", self.client.endpoint(), &self.subscription_id, &self.resource_group_name, &self.rule_name ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); url.query_pairs_mut().append_pair("api-version", "2021-08-01"); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => Ok(Response::Ok200), http::StatusCode::NO_CONTENT => Ok(Response::NoContent204), status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorContract = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } }
{ list_by_resource_group::Builder { client: self.0.clone(), subscription_id: subscription_id.into(), resource_group_name: resource_group_name.into(), } }
account_internal_test.go
package toshl import ( "github.com/stretchr/testify/assert" "testing"
func TestAccountGetQueryString(t *testing.T) { a := AccountQueryParams{ Page: 2, PerPage: 1, Since: time.Date(2016, 11, 6, 13, 28, 0, 0, time.Local), Status: "active", IncludeDeleted: true, } assert.Equal(t, a.getQueryString(), `include_deleted=true&page=2&per_page=1&`+ `since=2016-11-06T13%3A28%3A00Z&status=active`) }
"time" )
auth.ts
import { action, autorun, computed, observable } from 'mobx'; import { decode } from 'jwt-simple'; import { SessionToken } from 'gearworks-route'; import { User } from 'app'; const AUTH_STORAGE_NAME = "gearworks-auth"; class
{ constructor() { this.token = localStorage.getItem(AUTH_STORAGE_NAME) || ""; if (this.token) { // Decode the token without verifying it. Verification will happen on the server. this.session = decode(this.token, undefined, true); } autorun("AuthStore-autorun", (runner) => { // Persist the auth changes to localstorage localStorage.setItem(AUTH_STORAGE_NAME, this.token); }); } @observable token: string; @observable session: SessionToken<User>; @computed get sessionIsInvalid() { return !this.token || !this.session || (this.session.exp * 1000 < Date.now()); } @action login(token: string) { this.session = decode(token, undefined, true); this.token = token; } @action logout() { this.session = {} as any; this.token = ""; } } export const AuthStore = new AuthStoreFactory();
AuthStoreFactory
core.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Core Keras layers. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import sys import types as python_types import warnings import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.keras import activations from tensorflow.python.keras import backend as K from tensorflow.python.keras import constraints from tensorflow.python.keras import initializers from tensorflow.python.keras import regularizers from tensorflow.python.keras.engine.base_layer import Layer from tensorflow.python.keras.engine.input_spec import InputSpec from tensorflow.python.keras.utils import conv_utils from tensorflow.python.keras.utils import generic_utils from tensorflow.python.keras.utils import tf_utils from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.ops import sparse_ops from tensorflow.python.ops import standard_ops from tensorflow.python.ops import variable_scope from tensorflow.python.util import nest from tensorflow.python.util import tf_inspect from tensorflow.python.util.tf_export import keras_export @keras_export('keras.layers.Masking') class Masking(Layer): """Masks a sequence by using a mask value to skip timesteps. For each timestep in the input tensor (dimension #1 in the tensor), if all values in the input tensor at that timestep are equal to `mask_value`, then the timestep will be masked (skipped) in all downstream layers (as long as they support masking). If any downstream layer does not support masking yet receives such an input mask, an exception will be raised. Example: Consider a Numpy data array `x` of shape `(samples, timesteps, features)`, to be fed to an LSTM layer. You want to mask timestep #3 and #5 because you lack data for these timesteps. You can: - Set `x[:, 3, :] = 0.` and `x[:, 5, :] = 0.` - Insert a `Masking` layer with `mask_value=0.` before the LSTM layer: ```python samples, timesteps, features = 32, 10, 8 inputs = np.random.random([samples, timesteps, features]).astype(np.float32) inputs[:, 3, :] = 0. inputs[:, 5, :] = 0. model = tf.keras.models.Sequential() model.add(tf.keras.layers.Masking(mask_value=0., input_shape=(timesteps, features))) model.add(tf.keras.layers.LSTM(32)) output = model(inputs) # The time step 3 and 5 will be skipped from LSTM calculation. ``` See [the masking and padding guide](https://www.tensorflow.org/guide/keras/masking_and_padding) for more details. """ def __init__(self, mask_value=0., **kwargs): super(Masking, self).__init__(**kwargs) self.supports_masking = True self.mask_value = mask_value self._compute_output_and_mask_jointly = True def compute_mask(self, inputs, mask=None): return K.any(math_ops.not_equal(inputs, self.mask_value), axis=-1) def call(self, inputs): boolean_mask = K.any( math_ops.not_equal(inputs, self.mask_value), axis=-1, keepdims=True) outputs = inputs * math_ops.cast(boolean_mask, inputs.dtype) # Compute the mask and outputs simultaneously. outputs._keras_mask = array_ops.squeeze(boolean_mask, axis=-1) # pylint: disable=protected-access return outputs def compute_output_shape(self, input_shape): return input_shape def get_config(self): config = {'mask_value': self.mask_value} base_config = super(Masking, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Dropout') class Dropout(Layer): """Applies Dropout to the input. Dropout consists in randomly setting a fraction `rate` of input units to 0 at each update during training time, which helps prevent overfitting. Arguments: rate: Float between 0 and 1. Fraction of the input units to drop. noise_shape: 1D integer tensor representing the shape of the binary dropout mask that will be multiplied with the input. For instance, if your inputs have shape `(batch_size, timesteps, features)` and you want the dropout mask to be the same for all timesteps, you can use `noise_shape=(batch_size, 1, features)`. seed: A Python integer to use as random seed. Call arguments: inputs: Input tensor (of any rank). training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing). """ def __init__(self, rate, noise_shape=None, seed=None, **kwargs): super(Dropout, self).__init__(**kwargs) self.rate = rate self.noise_shape = noise_shape self.seed = seed self.supports_masking = True def _get_noise_shape(self, inputs): # Subclasses of `Dropout` may implement `_get_noise_shape(self, inputs)`, # which will override `self.noise_shape`, and allows for custom noise # shapes with dynamically sized inputs. if self.noise_shape is None: return None concrete_inputs_shape = array_ops.shape(inputs) noise_shape = [] for i, value in enumerate(self.noise_shape): noise_shape.append(concrete_inputs_shape[i] if value is None else value) return ops.convert_to_tensor(noise_shape) def call(self, inputs, training=None): if training is None: training = K.learning_phase() def dropped_inputs(): return nn.dropout( inputs, noise_shape=self._get_noise_shape(inputs), seed=self.seed, rate=self.rate) output = tf_utils.smart_cond(training, dropped_inputs, lambda: array_ops.identity(inputs)) return output def compute_output_shape(self, input_shape): return input_shape def get_config(self): config = { 'rate': self.rate, 'noise_shape': self.noise_shape, 'seed': self.seed } base_config = super(Dropout, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.SpatialDropout1D') class SpatialDropout1D(Dropout): """Spatial 1D version of Dropout. This version performs the same function as Dropout, however it drops entire 1D feature maps instead of individual elements. If adjacent frames within feature maps are strongly correlated (as is normally the case in early convolution layers) then regular dropout will not regularize the activations and will otherwise just result in an effective learning rate decrease. In this case, SpatialDropout1D will help promote independence between feature maps and should be used instead. Arguments: rate: Float between 0 and 1. Fraction of the input units to drop. Call arguments: inputs: A 3D tensor. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing). Input shape: 3D tensor with shape: `(samples, timesteps, channels)` Output shape: Same as input. References: - [Efficient Object Localization Using Convolutional Networks](https://arxiv.org/abs/1411.4280) """ def __init__(self, rate, **kwargs): super(SpatialDropout1D, self).__init__(rate, **kwargs) self.input_spec = InputSpec(ndim=3) def _get_noise_shape(self, inputs): input_shape = array_ops.shape(inputs) noise_shape = (input_shape[0], 1, input_shape[2]) return noise_shape @keras_export('keras.layers.SpatialDropout2D') class SpatialDropout2D(Dropout): """Spatial 2D version of Dropout. This version performs the same function as Dropout, however it drops entire 2D feature maps instead of individual elements. If adjacent pixels within feature maps are strongly correlated (as is normally the case in early convolution layers) then regular dropout will not regularize the activations and will otherwise just result in an effective learning rate decrease. In this case, SpatialDropout2D will help promote independence between feature maps and should be used instead. Arguments: rate: Float between 0 and 1. Fraction of the input units to drop. data_format: 'channels_first' or 'channels_last'. In 'channels_first' mode, the channels dimension (the depth) is at index 1, in 'channels_last' mode is it at index 3. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". Call arguments: inputs: A 4D tensor. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing). Input shape: 4D tensor with shape: `(samples, channels, rows, cols)` if data_format='channels_first' or 4D tensor with shape: `(samples, rows, cols, channels)` if data_format='channels_last'. Output shape: Same as input. References: - [Efficient Object Localization Using Convolutional Networks](https://arxiv.org/abs/1411.4280) """ def __init__(self, rate, data_format=None, **kwargs): super(SpatialDropout2D, self).__init__(rate, **kwargs) if data_format is None: data_format = K.image_data_format() if data_format not in {'channels_last', 'channels_first'}: raise ValueError('data_format must be in ' '{"channels_last", "channels_first"}') self.data_format = data_format self.input_spec = InputSpec(ndim=4) def _get_noise_shape(self, inputs): input_shape = array_ops.shape(inputs) if self.data_format == 'channels_first': return (input_shape[0], input_shape[1], 1, 1) elif self.data_format == 'channels_last': return (input_shape[0], 1, 1, input_shape[3]) @keras_export('keras.layers.SpatialDropout3D') class SpatialDropout3D(Dropout): """Spatial 3D version of Dropout. This version performs the same function as Dropout, however it drops entire 3D feature maps instead of individual elements. If adjacent voxels within feature maps are strongly correlated (as is normally the case in early convolution layers) then regular dropout will not regularize the activations and will otherwise just result in an effective learning rate decrease. In this case, SpatialDropout3D will help promote independence between feature maps and should be used instead. Arguments: rate: Float between 0 and 1. Fraction of the input units to drop. data_format: 'channels_first' or 'channels_last'. In 'channels_first' mode, the channels dimension (the depth) is at index 1, in 'channels_last' mode is it at index 4. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". Call arguments: inputs: A 5D tensor. training: Python boolean indicating whether the layer should behave in training mode (adding dropout) or in inference mode (doing nothing). Input shape: 5D tensor with shape: `(samples, channels, dim1, dim2, dim3)` if data_format='channels_first' or 5D tensor with shape: `(samples, dim1, dim2, dim3, channels)` if data_format='channels_last'. Output shape: Same as input. References: - [Efficient Object Localization Using Convolutional Networks](https://arxiv.org/abs/1411.4280) """ def __init__(self, rate, data_format=None, **kwargs): super(SpatialDropout3D, self).__init__(rate, **kwargs) if data_format is None: data_format = K.image_data_format() if data_format not in {'channels_last', 'channels_first'}: raise ValueError('data_format must be in ' '{"channels_last", "channels_first"}') self.data_format = data_format self.input_spec = InputSpec(ndim=5) def _get_noise_shape(self, inputs): input_shape = array_ops.shape(inputs) if self.data_format == 'channels_first': return (input_shape[0], input_shape[1], 1, 1, 1) elif self.data_format == 'channels_last': return (input_shape[0], 1, 1, 1, input_shape[4]) @keras_export('keras.layers.Activation') class Activation(Layer): """Applies an activation function to an output. Arguments: activation: Activation function, such as `tf.nn.relu`, or string name of built-in activation function, such as "relu". Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input. """ def
(self, activation, **kwargs): super(Activation, self).__init__(**kwargs) self.supports_masking = True self.activation = activations.get(activation) def call(self, inputs): return self.activation(inputs) def compute_output_shape(self, input_shape): return input_shape def get_config(self): config = {'activation': activations.serialize(self.activation)} base_config = super(Activation, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Reshape') class Reshape(Layer): """Reshapes an output to a certain shape. Arguments: target_shape: Target shape. Tuple of integers, does not include the samples dimension (batch size). Input shape: Arbitrary, although all dimensions in the input shaped must be fixed. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: `(batch_size,) + target_shape` Example: ```python # as first layer in a Sequential model model = Sequential() model.add(Reshape((3, 4), input_shape=(12,))) # now: model.output_shape == (None, 3, 4) # note: `None` is the batch dimension # as intermediate layer in a Sequential model model.add(Reshape((6, 2))) # now: model.output_shape == (None, 6, 2) # also supports shape inference using `-1` as dimension model.add(Reshape((-1, 2, 2))) # now: model.output_shape == (None, None, 2, 2) ``` """ def __init__(self, target_shape, **kwargs): super(Reshape, self).__init__(**kwargs) self.target_shape = tuple(target_shape) def _fix_unknown_dimension(self, input_shape, output_shape): """Find and replace a missing dimension in an output shape. This is a near direct port of the internal Numpy function `_fix_unknown_dimension` in `numpy/core/src/multiarray/shape.c` Arguments: input_shape: Shape of array being reshaped output_shape: Desired shape of the array with at most a single -1 which indicates a dimension that should be derived from the input shape. Returns: The new output shape with a -1 replaced with its computed value. Raises: ValueError: If the total array size of the output_shape is different than the input_shape, or more than one unknown dimension is specified. """ output_shape = list(output_shape) msg = 'total size of new array must be unchanged' known, unknown = 1, None for index, dim in enumerate(output_shape): if dim < 0: if unknown is None: unknown = index else: raise ValueError('Can only specify one unknown dimension.') else: known *= dim original = np.prod(input_shape, dtype=int) if unknown is not None: if known == 0 or original % known != 0: raise ValueError(msg) output_shape[unknown] = original // known elif original != known: raise ValueError(msg) return output_shape def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() if None in input_shape[1:]: output_shape = [input_shape[0]] # input shape (partially) unknown? replace -1's with None's output_shape += tuple(s if s != -1 else None for s in self.target_shape) else: output_shape = [input_shape[0]] output_shape += self._fix_unknown_dimension(input_shape[1:], self.target_shape) return tensor_shape.TensorShape(output_shape) def call(self, inputs): return array_ops.reshape(inputs, (array_ops.shape(inputs)[0],) + self.target_shape) def get_config(self): config = {'target_shape': self.target_shape} base_config = super(Reshape, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Permute') class Permute(Layer): """Permutes the dimensions of the input according to a given pattern. Useful for e.g. connecting RNNs and convnets together. Example: ```python model = Sequential() model.add(Permute((2, 1), input_shape=(10, 64))) # now: model.output_shape == (None, 64, 10) # note: `None` is the batch dimension ``` Arguments: dims: Tuple of integers. Permutation pattern, does not include the samples dimension. Indexing starts at 1. For instance, `(2, 1)` permutes the first and second dimensions of the input. Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same as the input shape, but with the dimensions re-ordered according to the specified pattern. """ def __init__(self, dims, **kwargs): super(Permute, self).__init__(**kwargs) self.dims = tuple(dims) if sorted(dims) != list(range(1, len(dims) + 1)): raise ValueError( 'Invalid permutation `dims` for Permute Layer: %s. ' 'The set of indices in `dims` must be consecutive and start from 1.' % (dims,)) self.input_spec = InputSpec(ndim=len(self.dims) + 1) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() output_shape = copy.copy(input_shape) for i, dim in enumerate(self.dims): target_dim = input_shape[dim] output_shape[i + 1] = target_dim return tensor_shape.TensorShape(output_shape) def call(self, inputs): return array_ops.transpose(inputs, perm=(0,) + self.dims) def get_config(self): config = {'dims': self.dims} base_config = super(Permute, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Flatten') class Flatten(Layer): """Flattens the input. Does not affect the batch size. If inputs are shaped `(batch,)` without a channel dimension, then flattening adds an extra channel dimension and output shapes are `(batch, 1)`. Arguments: data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, ...)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". Example: ```python model = Sequential() model.add(Convolution2D(64, 3, 3, border_mode='same', input_shape=(3, 32, 32))) # now: model.output_shape == (None, 64, 32, 32) model.add(Flatten()) # now: model.output_shape == (None, 65536) ``` """ def __init__(self, data_format=None, **kwargs): super(Flatten, self).__init__(**kwargs) self.data_format = conv_utils.normalize_data_format(data_format) self.input_spec = InputSpec(min_ndim=1) def call(self, inputs): if (self.data_format == 'channels_first' and K.ndim(inputs) is not None and K.ndim(inputs) > 1): permutation = [0] permutation.extend([i for i in range(2, K.ndim(inputs))]) permutation.append(1) inputs = array_ops.transpose(inputs, perm=permutation) input_shape = inputs.shape if input_shape[1:].is_fully_defined(): flattened_dim = tensor_shape.dimension_value( np.prod(input_shape[1:], dtype=int)) # Temporary fix for integer overflow issue. if flattened_dim > np.iinfo(np.int32).max: shape_dtype = dtypes.int64 else: shape_dtype = dtypes.int32 outputs = array_ops.reshape( inputs, constant_op.constant((-1, flattened_dim), dtype=shape_dtype)) else: batch_size = tensor_shape.dimension_value(inputs.shape[0]) if batch_size: # Temporary fix for integer overflow issue. if batch_size > np.iinfo(np.int32).max: shape_dtype = dtypes.int64 else: shape_dtype = dtypes.int32 outputs = array_ops.reshape( inputs, constant_op.constant((batch_size, -1), dtype=shape_dtype)) else: outputs = array_ops.reshape(inputs, (array_ops.shape(inputs)[0], -1)) if not context.executing_eagerly(): outputs.set_shape(self.compute_output_shape(inputs.shape)) return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.as_shape(input_shape).as_list() if not input_shape: output_shape = tensor_shape.TensorShape([1]) else: output_shape = [input_shape[0]] if all(input_shape[1:]): output_shape += [np.prod(input_shape[1:], dtype=int)] else: output_shape += [None] return tensor_shape.TensorShape(output_shape) def get_config(self): config = {'data_format': self.data_format} base_config = super(Flatten, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.RepeatVector') class RepeatVector(Layer): """Repeats the input n times. Example: ```python model = Sequential() model.add(Dense(32, input_dim=32)) # now: model.output_shape == (None, 32) # note: `None` is the batch dimension model.add(RepeatVector(3)) # now: model.output_shape == (None, 3, 32) ``` Arguments: n: Integer, repetition factor. Input shape: 2D tensor of shape `(num_samples, features)`. Output shape: 3D tensor of shape `(num_samples, n, features)`. """ def __init__(self, n, **kwargs): super(RepeatVector, self).__init__(**kwargs) self.n = n self.input_spec = InputSpec(ndim=2) def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape).as_list() return tensor_shape.TensorShape([input_shape[0], self.n, input_shape[1]]) def call(self, inputs): return K.repeat(inputs, self.n) def get_config(self): config = {'n': self.n} base_config = super(RepeatVector, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.Lambda') class Lambda(Layer): """Wraps arbitrary expressions as a `Layer` object. The `Lambda` layer exists so that arbitrary TensorFlow functions can be used when constructing `Sequential` and Functional API models. `Lambda` layers are best suited for simple operations or quick experimentation. For more advanced usecases, follow [this guide](https://www.tensorflow.org/alpha/guide/keras/custom_layers_and_models) for subclassing `tf.keras.layers.Layer`. The main reason to subclass `tf.keras.layers.Layer` instead of using a `Lambda` layer is saving and inspecting a Model. `Lambda` layers are saved by serializing the Python bytecode, whereas subclassed Layers can be saved via overriding their `get_config` method. Overriding `get_config` improves the portability of Models. Models that rely on subclassed Layers are also often easier to visualize and reason about. Examples: ```python # add a x -> x^2 layer model.add(Lambda(lambda x: x ** 2)) ``` ```python # add a layer that returns the concatenation # of the positive part of the input and # the opposite of the negative part def antirectifier(x): x -= K.mean(x, axis=1, keepdims=True) x = K.l2_normalize(x, axis=1) pos = K.relu(x) neg = K.relu(-x) return K.concatenate([pos, neg], axis=1) model.add(Lambda(antirectifier)) ``` Variables can be created within a `Lambda` layer. Like with other layers, these variables will be created only once and reused if the `Lambda` layer is called on new inputs. If creating more than one variable in a given `Lambda` instance, be sure to use a different name for each variable. Note that calling sublayers from within a `Lambda` is not supported. Example of variable creation: ```python def linear_transform(x): v1 = tf.Variable(1., name='multiplier') v2 = tf.Variable(0., name='bias') return x*v1 + v2 linear_layer = Lambda(linear_transform) model.add(linear_layer) model.add(keras.layers.Dense(10, activation='relu')) model.add(linear_layer) # Reuses existing Variables ``` Note that creating two instances of `Lambda` using the same function will *not* share Variables between the two instances. Each instance of `Lambda` will create and manage its own weights. Arguments: function: The function to be evaluated. Takes input tensor as first argument. output_shape: Expected output shape from function. This argument can be inferred if not explicitly provided. Can be a tuple or function. If a tuple, it only specifies the first dimension onward; sample dimension is assumed either the same as the input: `output_shape = (input_shape[0], ) + output_shape` or, the input is `None` and the sample dimension is also `None`: `output_shape = (None, ) + output_shape` If a function, it specifies the entire shape as a function of the input shape: `output_shape = f(input_shape)` mask: Either None (indicating no masking) or a callable with the same signature as the `compute_mask` layer method, or a tensor that will be returned as output mask regardless what the input is. arguments: Optional dictionary of keyword arguments to be passed to the function. Input shape: Arbitrary. Use the keyword argument input_shape (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Specified by `output_shape` argument """ def __init__(self, function, output_shape=None, mask=None, arguments=None, **kwargs): super(Lambda, self).__init__(**kwargs) self.function = function self.arguments = arguments if arguments else {} if mask is not None: self.supports_masking = True self.mask = mask self._supports_ragged_inputs = True self._output_shape = output_shape self._variable_dict = {} # These attributes are inherited from `Layer`. self._trainable_weights = [] self._non_trainable_weights = [] function_args = tf_inspect.getfullargspec(self.function).args self._fn_expects_training_arg = 'training' in function_args self._fn_expects_mask_arg = 'mask' in function_args @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): if self._output_shape is None: # Make use of existing autocomputation but provide Lambda-specific # error message. This is always safe to run even when the outer context # is Graph mode because Lambda layers don't have side effects such as # `add_loss`. with context.eager_mode(): try: return super(Lambda, self).compute_output_shape(input_shape) except NotImplementedError: raise NotImplementedError( 'We could not automatically infer the shape of the Lambda\'s ' 'output. Please specify `output_shape` for this Lambda.') if callable(self._output_shape): output_shapes = self._output_shape(input_shape) return tf_utils.convert_shapes(output_shapes, to_tuples=False) # Output shapes are passed directly and don't include batch dimension. input_tensor_shape = tf_utils.convert_shapes(input_shape, to_tuples=False) batch_size = nest.flatten(input_tensor_shape)[0][0] if input_shape else None def _add_batch(shape): return tensor_shape.TensorShape([batch_size] + shape.as_list()) output_shapes = tf_utils.convert_shapes(self._output_shape, to_tuples=False) return nest.map_structure(_add_batch, output_shapes) def call(self, inputs, mask=None, training=None): arguments = self.arguments if self._fn_expects_mask_arg: arguments['mask'] = mask if self._fn_expects_training_arg: arguments['training'] = training with variable_scope.variable_creator_scope(self._variable_creator): return self.function(inputs, **arguments) def _variable_creator(self, next_creator, **kwargs): name = kwargs['name'] if name in self._variable_dict: return self._variable_dict[name] var = next_creator(**kwargs) self._variable_dict[name] = var if var.trainable: self._trainable_weights.append(var) else: self._non_trainable_weights.append(var) K.track_variable(var) return var def compute_mask(self, inputs, mask=None): if callable(self.mask): return self.mask(inputs, mask) return self.mask def get_config(self): function_config = self._serialize_function_to_config(self.function) output_shape_config = self._serialize_function_to_config(self._output_shape, allow_raw=True) config = { 'function': function_config[0], 'function_type': function_config[1], 'module': function_config[2], 'output_shape': output_shape_config[0], 'output_shape_type': output_shape_config[1], 'output_shape_module': output_shape_config[2], } if self.mask is not None: mask_config = self._serialize_function_to_config(self.mask) config.update({ 'mask': mask_config[0], 'mask_type': mask_config[1], 'mask_module': mask_config[2] }) config['arguments'] = self.arguments base_config = super(Lambda, self).get_config() return dict(list(base_config.items()) + list(config.items())) def _serialize_function_to_config(self, inputs, allow_raw=False): if isinstance(inputs, python_types.LambdaType): output = generic_utils.func_dump(inputs) output_type = 'lambda' module = inputs.__module__ elif callable(inputs): output = inputs.__name__ output_type = 'function' module = inputs.__module__ elif allow_raw: output = inputs output_type = 'raw' module = None else: raise ValueError( 'Invalid input for serialization, type: %s ' % type(inputs)) return output, output_type, module @classmethod def from_config(cls, config, custom_objects=None): config = config.copy() function = cls._parse_function_from_config( config, custom_objects, 'function', 'module', 'function_type') output_shape = cls._parse_function_from_config( config, custom_objects, 'output_shape', 'output_shape_module', 'output_shape_type') if 'mask' in config: mask = cls._parse_function_from_config( config, custom_objects, 'mask', 'mask_module', 'mask_type') else: mask = None config['function'] = function config['output_shape'] = output_shape config['mask'] = mask # If arguments were numpy array, they have been saved as # list. We need to recover the ndarray if 'arguments' in config: for key in config['arguments']: if isinstance(config['arguments'][key], dict): arg_dict = config['arguments'][key] if 'type' in arg_dict and arg_dict['type'] == 'ndarray': # Overwrite the argument with its numpy translation config['arguments'][key] = np.array(arg_dict['value']) return cls(**config) @classmethod def _parse_function_from_config( cls, config, custom_objects, func_attr_name, module_attr_name, func_type_attr_name): globs = globals() module = config.pop(module_attr_name, None) if module in sys.modules: globs.update(sys.modules[module].__dict__) elif module is not None: # Note: we don't know the name of the function if it's a lambda. warnings.warn('{} is not loaded, but a Lambda layer uses it. ' 'It may cause errors.'.format(module) , UserWarning) if custom_objects: globs.update(custom_objects) function_type = config.pop(func_type_attr_name) if function_type == 'function': # Simple lookup in custom objects function = generic_utils.deserialize_keras_object( config[func_attr_name], custom_objects=custom_objects, printable_module_name='function in Lambda layer') elif function_type == 'lambda': # Unsafe deserialization from bytecode function = generic_utils.func_load( config[func_attr_name], globs=globs) elif function_type == 'raw': function = config[func_attr_name] else: raise TypeError('Unknown function type:', function_type) return function @keras_export('keras.layers.Dense') class Dense(Layer): """Just your regular densely-connected NN layer. `Dense` implements the operation: `output = activation(dot(input, kernel) + bias)` where `activation` is the element-wise activation function passed as the `activation` argument, `kernel` is a weights matrix created by the layer, and `bias` is a bias vector created by the layer (only applicable if `use_bias` is `True`). Note: If the input to the layer has a rank greater than 2, then it is flattened prior to the initial dot product with `kernel`. Example: ```python # as first layer in a sequential model: model = Sequential() model.add(Dense(32, input_shape=(16,))) # now the model will take as input arrays of shape (*, 16) # and output arrays of shape (*, 32) # after the first layer, you don't need to specify # the size of the input anymore: model.add(Dense(32)) ``` Arguments: units: Positive integer, dimensionality of the output space. activation: Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. activity_regularizer: Regularizer function applied to the output of the layer (its "activation").. kernel_constraint: Constraint function applied to the `kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. Input shape: N-D tensor with shape: `(batch_size, ..., input_dim)`. The most common situation would be a 2D input with shape `(batch_size, input_dim)`. Output shape: N-D tensor with shape: `(batch_size, ..., units)`. For instance, for a 2D input with shape `(batch_size, input_dim)`, the output would have shape `(batch_size, units)`. """ def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs): if 'input_shape' not in kwargs and 'input_dim' in kwargs: kwargs['input_shape'] = (kwargs.pop('input_dim'),) super(Dense, self).__init__( activity_regularizer=regularizers.get(activity_regularizer), **kwargs) self.units = int(units) if not isinstance(units, int) else units self.activation = activations.get(activation) self.use_bias = use_bias self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.supports_masking = True self.input_spec = InputSpec(min_ndim=2) def build(self, input_shape): dtype = dtypes.as_dtype(self.dtype or K.floatx()) if not (dtype.is_floating or dtype.is_complex): raise TypeError('Unable to build `Dense` layer with non-floating point ' 'dtype %s' % (dtype,)) input_shape = tensor_shape.TensorShape(input_shape) if tensor_shape.dimension_value(input_shape[-1]) is None: raise ValueError('The last dimension of the inputs to `Dense` ' 'should be defined. Found `None`.') last_dim = tensor_shape.dimension_value(input_shape[-1]) self.input_spec = InputSpec(min_ndim=2, axes={-1: last_dim}) self.kernel = self.add_weight( 'kernel', shape=[last_dim, self.units], initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, dtype=self.dtype, trainable=True) if self.use_bias: self.bias = self.add_weight( 'bias', shape=[self.units,], initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, dtype=self.dtype, trainable=True) else: self.bias = None self.built = True def call(self, inputs): rank = len(inputs.shape) if rank > 2: # Broadcasting is required for the inputs. outputs = standard_ops.tensordot(inputs, self.kernel, [[rank - 1], [0]]) # Reshape the output back to the original ndim of the input. if not context.executing_eagerly(): shape = inputs.shape.as_list() output_shape = shape[:-1] + [self.units] outputs.set_shape(output_shape) else: inputs = math_ops.cast(inputs, self._compute_dtype) if K.is_sparse(inputs): outputs = sparse_ops.sparse_tensor_dense_matmul(inputs, self.kernel) else: outputs = gen_math_ops.mat_mul(inputs, self.kernel) if self.use_bias: outputs = nn.bias_add(outputs, self.bias) if self.activation is not None: return self.activation(outputs) # pylint: disable=not-callable return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) input_shape = input_shape.with_rank_at_least(2) if tensor_shape.dimension_value(input_shape[-1]) is None: raise ValueError( 'The innermost dimension of input_shape must be defined, but saw: %s' % input_shape) return input_shape[:-1].concatenate(self.units) def get_config(self): config = { 'units': self.units, 'activation': activations.serialize(self.activation), 'use_bias': self.use_bias, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint) } base_config = super(Dense, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.ActivityRegularization') class ActivityRegularization(Layer): """Layer that applies an update to the cost function based input activity. Arguments: l1: L1 regularization factor (positive float). l2: L2 regularization factor (positive float). Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as input. """ def __init__(self, l1=0., l2=0., **kwargs): super(ActivityRegularization, self).__init__( activity_regularizer=regularizers.L1L2(l1=l1, l2=l2), **kwargs) self.supports_masking = True self.l1 = l1 self.l2 = l2 def compute_output_shape(self, input_shape): return input_shape def get_config(self): config = {'l1': self.l1, 'l2': self.l2} base_config = super(ActivityRegularization, self).get_config() return dict(list(base_config.items()) + list(config.items())) @keras_export('keras.layers.DropConnectDense') class DropConnectDense(Layer): """Just your regular densely-connected NN layer. `Dense` implements the operation: `output = activation(dot(input, kernel) + bias)` where `activation` is the element-wise activation function passed as the `activation` argument, `kernel` is a weights matrix created by the layer, and `bias` is a bias vector created by the layer (only applicable if `use_bias` is `True`). Note: If the input to the layer has a rank greater than 2, then it is flattened prior to the initial dot product with `kernel`. Example: ```python # as first layer in a sequential model: model = Sequential() model.add(Dense(32, input_shape=(16,))) # now the model will take as input arrays of shape (*, 16) # and output arrays of shape (*, 32) # after the first layer, you don't need to specify # the size of the input anymore: model.add(Dense(32)) ``` Arguments: units: Positive integer, dimensionality of the output space. activation: Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: `a(x) = x`). use_bias: Boolean, whether the layer uses a bias vector. kernel_initializer: Initializer for the `kernel` weights matrix. bias_initializer: Initializer for the bias vector. kernel_regularizer: Regularizer function applied to the `kernel` weights matrix. bias_regularizer: Regularizer function applied to the bias vector. activity_regularizer: Regularizer function applied to the output of the layer (its "activation").. kernel_constraint: Constraint function applied to the `kernel` weights matrix. bias_constraint: Constraint function applied to the bias vector. kernel_dropout: Float between 0 and 1. Fraction of the weight units to drop. unit_dropout: Float between 0 and 1. Fraction of the inputs to drop. use_mc_dropout: Bool when True layer always acts like in "train mode" so dropout can be applied also in inference mode Input shape: N-D tensor with shape: `(batch_size, ..., input_dim)`. The most common situation would be a 2D input with shape `(batch_size, input_dim)`. Output shape: N-D tensor with shape: `(batch_size, ..., units)`. For instance, for a 2D input with shape `(batch_size, input_dim)`, the output would have shape `(batch_size, units)`. """ def __init__(self, units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, kernel_dropout=0., unit_dropout=0., use_mc_dropout=False, **kwargs): if 'input_shape' not in kwargs and 'input_dim' in kwargs: kwargs['input_shape'] = (kwargs.pop('input_dim'),) super(DropConnectDense, self).__init__( activity_regularizer=regularizers.get(activity_regularizer), **kwargs) self.units = int(units) if not isinstance(units, int) else units self.activation = activations.get(activation) self.use_bias = use_bias self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.kernel_regularizer = regularizers.get(kernel_regularizer) self.bias_regularizer = regularizers.get(bias_regularizer) self.kernel_constraint = constraints.get(kernel_constraint) self.bias_constraint = constraints.get(bias_constraint) self.kernel_dropout = min(1., max(0., kernel_dropout)) self.unit_dropout = min(1., max(0., unit_dropout)) self.use_mc_dropout = use_mc_dropout self.supports_masking = True self.input_spec = InputSpec(min_ndim=2) def build(self, input_shape): dtype = dtypes.as_dtype(self.dtype or K.floatx()) if not (dtype.is_floating or dtype.is_complex): raise TypeError('Unable to build `Dense` layer with non-floating point ' 'dtype %s' % (dtype,)) input_shape = tensor_shape.TensorShape(input_shape) if tensor_shape.dimension_value(input_shape[-1]) is None: raise ValueError('The last dimension of the inputs to `Dense` ' 'should be defined. Found `None`.') last_dim = tensor_shape.dimension_value(input_shape[-1]) self.input_spec = InputSpec(min_ndim=2, axes={-1: last_dim}) self.kernel = self.add_weight( 'kernel', shape=[last_dim, self.units], initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, constraint=self.kernel_constraint, dtype=self.dtype, trainable=True) if self.use_bias: self.bias = self.add_weight( 'bias', shape=[self.units,], initializer=self.bias_initializer, regularizer=self.bias_regularizer, constraint=self.bias_constraint, dtype=self.dtype, trainable=True) else: self.bias = None self.built = True def call(self, inputs, training=None): if training is None: training = K.learning_phase() if self.use_mc_dropout: training = True #units dropout def drop_inputs(): return K.dropout(inputs, self.unit_dropout) if 0. < self.unit_dropout < 1.: inputs = K.in_train_phase(drop_inputs, inputs, training=training) #kernel dropout ones = array_ops.ones_like(self.kernel) def dropped_weight_connections(): return K.dropout(ones, self.kernel_dropout) * (1 - self.kernel_dropout) if 0. < self.kernel_dropout < 1.: kern_dp_mask = K.in_train_phase(dropped_weight_connections, ones, training=training) else: kern_dp_mask = ones rank = len(inputs.shape) if rank > 2: # Broadcasting is required for the inputs. outputs = standard_ops.tensordot(inputs, self.kernel * kern_dp_mask, [[rank - 1], [0]]) # Reshape the output back to the original ndim of the input. if not context.executing_eagerly(): shape = inputs.shape.as_list() output_shape = shape[:-1] + [self.units] outputs.set_shape(output_shape) else: inputs = math_ops.cast(inputs, self._compute_dtype) if K.is_sparse(inputs): outputs = sparse_ops.sparse_tensor_dense_matmul(inputs, self.kernel * kern_dp_mask) else: outputs = gen_math_ops.mat_mul(inputs, self.kernel * kern_dp_mask) if self.use_bias: outputs = nn.bias_add(outputs, self.bias) if self.activation is not None: return self.activation(outputs) # pylint: disable=not-callable return outputs def compute_output_shape(self, input_shape): input_shape = tensor_shape.TensorShape(input_shape) input_shape = input_shape.with_rank_at_least(2) if tensor_shape.dimension_value(input_shape[-1]) is None: raise ValueError( 'The innermost dimension of input_shape must be defined, but saw: %s' % input_shape) return input_shape[:-1].concatenate(self.units) def get_config(self): config = { 'units': self.units, 'activation': activations.serialize(self.activation), 'use_bias': self.use_bias, 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'bias_initializer': initializers.serialize(self.bias_initializer), 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer), 'bias_regularizer': regularizers.serialize(self.bias_regularizer), 'activity_regularizer': regularizers.serialize(self.activity_regularizer), 'kernel_constraint': constraints.serialize(self.kernel_constraint), 'bias_constraint': constraints.serialize(self.bias_constraint), 'kernel_dropout': self.kernel_dropout, 'unit_dropout': self.unit_dropout, 'use_mc_dropout': self.use_mc_dropout } base_config = super(DropConnectDense, self).get_config() return dict(list(base_config.items()) + list(config.items()))
__init__
camera.py
import numpy as np import torch from scipy.spatial.transform import Rotation as Rot import pdb import math def get_camera_mat(fov=49.13, invert=True): # fov = 2 * arctan( sensor / (2 * focal)) # focal = (sensor / 2) * 1 / (tan(0.5 * fov)) # in our case, sensor = 2 as pixels are in [-1, 1] focal = 1. / np.tan(0.5 * fov * np.pi/180.) focal = focal.astype(np.float32) mat = torch.tensor([ [focal, 0., 0., 0.], [0., focal, 0., 0.], [0., 0., 1, 0.], [0., 0., 0., 1.] ]).reshape(1, 4, 4) if invert: mat = torch.inverse(mat) return mat def get_random_pose(u, v, range_radius, batch_size=16, # batch size 유동적으로 바꿀 수 있도록! invert=False): # edit mira start if isinstance(u, int): device = 'cpu' u = torch.zeros(batch_size,).to(device) v = torch.ones(batch_size,).to(device) * 0.25 loc = sample_on_sphere(u, v, size=(batch_size)) radius = range_radius[0] + \ torch.rand(batch_size) * (range_radius[1] - range_radius[0]) if loc.is_cuda: radius = radius.cuda() loc = loc * radius.unsqueeze(-1) R = look_at(loc) RT = torch.eye(4).reshape(1, 4, 4).repeat(batch_size, 1, 1) RT[:, :3, :3] = R RT[:, :3, -1] = loc if invert: RT = torch.inverse(RT) return radius, RT def get_middle_pose(range_u, range_v, range_radius, batch_size=32, invert=False): u_m, u_v, r_v = sum(range_u) * 0.5, sum(range_v) * \ 0.5, sum(range_radius) * 0.5 loc = sample_on_sphere((u_m, u_m), (u_v, u_v), size=(batch_size)) radius = torch.ones(batch_size) * r_v loc = loc * radius.unsqueeze(-1) R = look_at(loc) RT = torch.eye(4).reshape(1, 4, 4).repeat(batch_size, 1, 1) RT[:, :3, :3] = R RT[:, :3, -1] = loc if invert: RT = torch.inverse(RT) return RT def get_camera_pose(range_
ge_r, val_u=0.5, val_v=0.5, val_r=0.5, batch_size=32, invert=False): u0, ur = range_u[0], range_u[1] - range_u[0] v0, vr = range_v[0], range_v[1] - range_v[0] r0, rr = range_r[0], range_r[1] - range_r[0] u = u0 + val_u * ur v = v0 + val_v * vr r = r0 + val_r * rr loc = sample_on_sphere((u, u), (v, v), size=(batch_size)) radius = torch.ones(batch_size) * r loc = loc * radius.unsqueeze(-1) R = look_at(loc) RT = torch.eye(4).reshape(1, 4, 4).repeat(batch_size, 1, 1) RT[:, :3, :3] = R RT[:, :3, -1] = loc if invert: RT = torch.inverse(RT) return RT # edit: np -> torch def to_sphere(u, v): theta = 2 * math.pi * u phi = torch.arccos(1 - 2 * v) cx = torch.sin(phi) * torch.cos(theta) cy = torch.sin(phi) * torch.sin(theta) cz = torch.cos(phi) return torch.stack([cx, cy, cz], dim=-1) def sample_on_sphere(u=None, v=None, size=(1,), to_pytorch=True): # range_u (0, 0) range_v (0.25, 0.25) sample = to_sphere(u, v) # sample expect to be (16, 3) if to_pytorch: sample = torch.tensor(sample).float() return sample def look_at(eye, at=np.array([0, 0, 0]), up=np.array([0, 0, 1]), eps=1e-5, to_pytorch=True): at = at.reshape(1, 3) up = up.reshape(1, 3) eye = eye.reshape(-1, 3) if isinstance(eye, torch.Tensor): if eye.is_cuda: device=torch.device('cuda:0') else: device=torch.device('cpu') # array at = torch.tensor(at).to(device).float() up = torch.tensor(up).to(device).float() up = up.repeat(eye.shape[0] // up.shape[0], 1) eps = torch.tensor([eps]).reshape(1, 1).repeat(up.shape[0], 1).to(device).float() z_axis = eye - at z_axis = z_axis / torch.max(torch.stack([torch.norm(z_axis, dim=1, keepdim=True), eps])) x_axis = torch.cross(up, z_axis) x_axis = x_axis / torch.max(torch.stack([torch.norm(x_axis, dim=1, keepdim=True), eps])) y_axis = torch.cross(z_axis, x_axis) y_axis = y_axis / torch.max(torch.stack([torch.norm(y_axis, dim=1, keepdim=True), eps])) r_mat = torch.cat( (x_axis.reshape(-1, 3, 1), y_axis.reshape(-1, 3, 1), z_axis.reshape( -1, 3, 1)), dim=2) else: print('pass here? oh my gaadd....') # 여기 안들어간다 오우쨔쓰!! up = up.repeat(eye.shape[0] // up.shape[0], axis = 0) eps = np.array([eps]).reshape(1, 1).repeat(up.shape[0], axis=0) z_axis = eye - at z_axis /= np.max(np.stack([np.linalg.norm(z_axis, axis=1, keepdims=True), eps])) x_axis = np.cross(up, z_axis) x_axis /= np.max(np.stack([np.linalg.norm(x_axis, axis=1, keepdims=True), eps])) y_axis = np.cross(z_axis, x_axis) y_axis /= np.max(np.stack([np.linalg.norm(y_axis, axis=1, keepdims=True), eps])) r_mat = np.concatenate( (x_axis.reshape(-1, 3, 1), y_axis.reshape(-1, 3, 1), z_axis.reshape( -1, 3, 1)), axis=2) if to_pytorch: r_mat = torch.tensor(r_mat).float() return r_mat def get_rotation_matrix(axis='z', value=0., batch_size=32): r = Rot.from_euler(axis, value * 2 * np.pi).as_dcm() r = torch.from_numpy(r).reshape(1, 3, 3).repeat(batch_size, 1, 1) return r
u, range_v, ran
response.py
class Status: OK = "OK" ERROR = "ERROR" class Response(dict): def __init__(self, status, data): super().__init__()
self["status"] = status self["data"] = data
tcp_listener.rs
use crate::net::{Incoming, SocketAddr, TcpStream}; use cap_primitives::{ambient_authority, AmbientAuthority}; #[cfg(not(windows))] use io_lifetimes::{AsFd, BorrowedFd, FromFd, IntoFd, OwnedFd}; #[cfg(windows)] use io_lifetimes::{AsSocket, BorrowedSocket, FromSocket, IntoSocket, OwnedSocket}; use std::{fmt, io, net}; #[cfg(not(windows))] use unsafe_io::os::posish::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use unsafe_io::OwnsRaw; #[cfg(windows)] use { std::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket}, unsafe_io::os::windows::{AsRawHandleOrSocket, IntoRawHandleOrSocket, RawHandleOrSocket}, }; /// A TCP socket server, listening for connections. /// /// This corresponds to [`std::net::TcpListener`]. /// /// Note that this `TcpListener` has no `bind` method. To bind it to a socket /// address, you must first obtain a [`Pool`] permitting the address, and /// then call [`Pool::bind_tcp_listener`]. /// /// [`Pool`]: struct.Pool.html /// [`Pool::bind_tcp_listener`]: struct.Pool.html#method.bind_tcp_listener pub struct TcpListener { std: net::TcpListener, } impl TcpListener { /// Constructs a new instance of `Self` from the given `std::net::TcpListener`. /// /// # Ambient Authority /// /// `std::net::TcpListener` is not sandboxed and may access any address that the host /// process has access to. #[inline] pub fn from_std(std: net::TcpListener, _: AmbientAuthority) -> Self { Self { std } } /// Returns the local socket address of this listener. /// /// This corresponds to [`std::net::TcpListener::local_addr`]. #[inline] pub fn
(&self) -> io::Result<SocketAddr> { self.std.local_addr() } /// Creates a new independently owned handle to the underlying socket. /// /// This corresponds to [`std::net::TcpListener::try_clone`]. #[inline] pub fn try_clone(&self) -> io::Result<Self> { let tcp_listener = self.std.try_clone()?; Ok(Self::from_std(tcp_listener, ambient_authority())) } /// Accept a new incoming connection from this listener. /// /// This corresponds to [`std::net::TcpListener::accept`]. #[inline] pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { self.std .accept() .map(|(tcp_stream, addr)| (TcpStream::from_std(tcp_stream, ambient_authority()), addr)) } /// Returns an iterator over the connections being received on this listener. /// /// This corresponds to [`std::net::TcpListener::incoming`]. #[inline] pub fn incoming(&self) -> Incoming { let incoming = self.std.incoming(); Incoming::from_std(incoming, ambient_authority()) } /// Sets the value for the `IP_TTL` option on this socket. /// /// This corresponds to [`std::net::TcpListener::set_ttl`]. #[inline] pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.std.set_ttl(ttl) } /// Gets the value of the `IP_TTL` option for this socket. /// /// This corresponds to [`std::net::TcpListener::ttl`]. #[inline] pub fn ttl(&self) -> io::Result<u32> { self.std.ttl() } /// Gets the value of the `SO_ERROR` option on this socket. /// /// This corresponds to [`std::net::TcpListener::take_error`]. #[inline] pub fn take_error(&self) -> io::Result<Option<io::Error>> { self.std.take_error() } /// Moves this TCP stream into or out of nonblocking mode. /// /// This corresponds to [`std::net::TcpListener::set_nonblocking`]. #[inline] pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { self.std.set_nonblocking(nonblocking) } } #[cfg(not(windows))] impl FromRawFd for TcpListener { #[inline] unsafe fn from_raw_fd(fd: RawFd) -> Self { Self::from_std(net::TcpListener::from_raw_fd(fd), ambient_authority()) } } #[cfg(not(windows))] impl FromFd for TcpListener { #[inline] fn from_fd(fd: OwnedFd) -> Self { Self::from_std(net::TcpListener::from_fd(fd), ambient_authority()) } } #[cfg(windows)] impl FromRawSocket for TcpListener { #[inline] unsafe fn from_raw_socket(socket: RawSocket) -> Self { Self::from_std( net::TcpListener::from_raw_socket(socket), ambient_authority(), ) } } #[cfg(windows)] impl FromSocket for TcpListener { #[inline] fn from_socket(socket: OwnedSocket) -> Self { Self::from_std(net::TcpListener::from_socket(socket), ambient_authority()) } } #[cfg(not(windows))] impl AsRawFd for TcpListener { #[inline] fn as_raw_fd(&self) -> RawFd { self.std.as_raw_fd() } } #[cfg(not(windows))] impl<'f> AsFd<'f> for &'f TcpListener { #[inline] fn as_fd(self) -> BorrowedFd<'f> { self.std.as_fd() } } #[cfg(windows)] impl AsRawSocket for TcpListener { #[inline] fn as_raw_socket(&self) -> RawSocket { self.std.as_raw_socket() } } #[cfg(windows)] impl<'s> AsSocket<'s> for &'s TcpListener { #[inline] fn as_socket(self) -> BorrowedSocket<'s> { self.std.as_socket() } } #[cfg(windows)] impl AsRawHandleOrSocket for TcpListener { #[inline] fn as_raw_handle_or_socket(&self) -> RawHandleOrSocket { self.std.as_raw_handle_or_socket() } } #[cfg(not(windows))] impl IntoRawFd for TcpListener { #[inline] fn into_raw_fd(self) -> RawFd { self.std.into_raw_fd() } } #[cfg(not(windows))] impl IntoFd for TcpListener { #[inline] fn into_fd(self) -> OwnedFd { self.std.into_fd() } } #[cfg(windows)] impl IntoRawSocket for TcpListener { #[inline] fn into_raw_socket(self) -> RawSocket { self.std.into_raw_socket() } } #[cfg(windows)] impl IntoSocket for TcpListener { #[inline] fn into_socket(self) -> OwnedSocket { self.std.into_socket() } } #[cfg(windows)] impl IntoRawHandleOrSocket for TcpListener { #[inline] fn into_raw_handle_or_socket(self) -> RawHandleOrSocket { self.std.into_raw_handle_or_socket() } } // Safety: `TcpListener` wraps a `net::TcpListener` which owns its handle. unsafe impl OwnsRaw for TcpListener {} impl fmt::Debug for TcpListener { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.std.fmt(f) } }
local_addr
engine.go
package cipher import ( "fmt" "regexp" "github.com/mvisonneau/s5/pkg/cipher/aes" "github.com/mvisonneau/s5/pkg/cipher/aws" "github.com/mvisonneau/s5/pkg/cipher/gcp" "github.com/mvisonneau/s5/pkg/cipher/pgp" "github.com/mvisonneau/s5/pkg/cipher/vault" "github.com/pkg/errors" ) const ( // InputRegexp is defining the syntax of an s5 input variable. InputRegexp string = `{{\s?s5:([A-Za-z0-9+\\/=]*)\s?}}` ) // Engine is an interface of supported/required commands for each cipher engine. type Engine interface { Cipher(string) (string, error) Decipher(string) (string, error) } // NewAESClient creates a AES client. func NewAESClient(key string) (*aes.Client, error) { c, err := aes.NewClient(&aes.Config{ Key: key, }) if err != nil { return c, errors.Wrap(err, "creating new AES engine client") } return c, nil } // NewAWSClient creates a AWS client. func NewAWSClient(kmsKeyArn string) (*aws.Client, error) { c, err := aws.NewClient(&aws.Config{ KmsKeyArn: kmsKeyArn, }) if err != nil { return c, errors.Wrap(err, "creating new AWS engine client") } return c, nil } // NewGCPClient creates a GCP client. func NewGCPClient(kmsKeyName string) (*gcp.Client, error) { c, err := gcp.NewClient(&gcp.Config{ KmsKeyName: kmsKeyName, }) if err != nil { return c, errors.Wrap(err, "creating new GCP engine client") } return c, nil } // NewPGPClient creates a PGP client. func NewPGPClient(publicKeyPath, privateKeyPath string) (*pgp.Client, error) { c, err := pgp.NewClient(&pgp.Config{ PublicKeyPath: publicKeyPath, PrivateKeyPath: privateKeyPath, }) if err != nil { return c, errors.Wrap(err, "creating new PGP engine client") } return c, nil } // NewVaultClient creates a Vault client. func NewVaultClient(key string) (*vault.Client, error) { c, err := vault.NewClient(&vault.Config{ Key: key, }) if err != nil { return c, errors.Wrap(err, "creating new Vault engine client") } return c, nil } // GenerateOutput return a ciphered string in a s5 format. func GenerateOutput(value string) string { return fmt.Sprintf("{{s5:%s}}", value) } // ParseInput retrieves ciphered value from a string in the s5 format. func ParseInput(value string) (string, error)
{ re := regexp.MustCompile(InputRegexp) if !re.MatchString(value) { return "", errors.New("invalid string format, should be '{{s5:*}}'") } return re.FindStringSubmatch(value)[1], nil }
deepspeed.py
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import contextlib import json import logging import os import platform from collections import OrderedDict from pathlib import Path from typing import Any, Callable, Dict, Generator, List, Mapping, Optional, Tuple, Union import torch from torch.optim import Optimizer import pytorch_lightning as pl from pytorch_lightning.overrides.base import _LightningModuleWrapperBase from pytorch_lightning.plugins.environments.cluster_environment import ClusterEnvironment from pytorch_lightning.plugins.io.checkpoint_plugin import CheckpointIO from pytorch_lightning.plugins.training_type.ddp import DDPPlugin from pytorch_lightning.trainer.optimizers import _get_default_scheduler_config from pytorch_lightning.trainer.states import TrainerFn from pytorch_lightning.utilities import AMPType from pytorch_lightning.utilities.apply_func import apply_to_collection from pytorch_lightning.utilities.distributed import log, rank_zero_info, rank_zero_only from pytorch_lightning.utilities.exceptions import MisconfigurationException from pytorch_lightning.utilities.imports import _DEEPSPEED_AVAILABLE from pytorch_lightning.utilities.seed import reset_seed from pytorch_lightning.utilities.types import _PATH, LRSchedulerTypeTuple from pytorch_lightning.utilities.warnings import rank_zero_warn, WarningCache warning_cache = WarningCache() if _DEEPSPEED_AVAILABLE: import deepspeed def remove_module_hooks(model: torch.nn.Module) -> None: # todo (tchaton) awaiting this feature to move upstream to DeepSpeed for module in model.modules(): module._backward_hooks = OrderedDict() module._is_full_backward_hook = None module._forward_hooks = OrderedDict() module._forward_pre_hooks = OrderedDict() module._state_dict_hooks = OrderedDict() module._load_state_dict_pre_hooks = OrderedDict() class LightningDeepSpeedModule(_LightningModuleWrapperBase): def __init__(self, pl_module: "pl.LightningModule", precision: int) -> None: super().__init__(pl_module) self.precision = precision def forward(self, *inputs, **kwargs): if self.precision == 16: inputs = self._move_float_tensors_to_half(inputs) return super().forward(*inputs, **kwargs) @staticmethod def batch_to(data): return data.half() def _move_float_tensors_to_half(self, batch: Any): batch = apply_to_collection(batch, (torch.FloatTensor, torch.cuda.FloatTensor), function=self.batch_to) return batch class DeepSpeedPlugin(DDPPlugin): distributed_backend = "deepspeed" DEEPSPEED_ENV_VAR = "PL_DEEPSPEED_CONFIG_PATH" def __init__( self, zero_optimization: bool = True, stage: int = 2, remote_device: str = "cpu", offload_optimizer: bool = False, offload_parameters: bool = False, offload_params_device: str = "cpu", nvme_path: str = "/local_nvme", params_buffer_count: int = 5, params_buffer_size: int = 1e8, max_in_cpu: int = 1e9, offload_optimizer_device: str = "cpu", optimizer_buffer_count: int = 4, block_size: int = 1048576, queue_depth: int = 8, single_submit: bool = False, overlap_events: bool = True, thread_count: int = 1, pin_memory: bool = False, sub_group_size: int = 1e12, contiguous_gradients: bool = True, overlap_comm: bool = True, allgather_partitions: bool = True, reduce_scatter: bool = True, allgather_bucket_size: int = 2e8, reduce_bucket_size: int = 2e8, zero_allow_untested_optimizer: bool = True, logging_batch_size_per_gpu: Union[str, int] = "auto", config: Optional[Union[Path, str, dict]] = None, logging_level: int = logging.WARN, num_nodes: Optional[int] = None, parallel_devices: Optional[List[torch.device]] = None, cluster_environment: Optional[ClusterEnvironment] = None, loss_scale: float = 0, initial_scale_power: int = 16, loss_scale_window: int = 1000, hysteresis: int = 2, min_loss_scale: int = 1, partition_activations: bool = False, cpu_checkpointing: bool = False, contiguous_memory_optimization: bool = False, synchronize_checkpoint_boundary: bool = False, load_full_weights: bool = False, partition_module: bool = True, ) -> None: """Provides capabilities to run training using the DeepSpeed library, with training optimizations for large billion parameter models. `For more information: https://pytorch- lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#deepspeed`. .. warning:: ``DeepSpeedPlugin`` is in beta and subject to change. Defaults have been set to enable ZeRO-Offload and some have been taken from the link below. These defaults have been set generally, but may require tuning for optimum performance based on your model size. `For more information: https://www.deepspeed.ai/docs/config-json/#zero-optimizations-for-fp16-training`. Arguments: zero_optimization: Enable ZeRO optimization. This is only compatible with precision=16. stage: Different stages of the ZeRO Optimizer. 0 is disabled, 1 is optimizer state partitioning, 2 is optimizer+gradient state partitioning, 3 is optimizer+gradient_parameter partitioning using the infinity engine. remote_device: Device to instantiate the model on initially (``cpu`` or ``nvme``). offload_optimizer: Enable offloading optimizer memory and computation to CPU or NVMe based on ``offload_optimizer_device``. offload_parameters: When using ZeRO Stage 3, Enable offloading parameter memory and computation to CPU or NVMe based on ``offload_params_device``. offload_params_device: When offloading parameters choose the device to offload to, ``cpu`` or ``nvme``. offload_optimizer_device: When offloading optimizer state choose the device to offload to, ``cpu`` or ``nvme``. params_buffer_count: Number of buffers in buffer pool for parameter offloading when ``offload_params_device`` is ``nvme``. params_buffer_size: Size of buffers in buffer pool for parameter offloading when ``offload_params_device`` is ``nvme``. max_in_cpu: Number of parameter elements to maintain in CPU memory when offloading to NVMe is enabled. nvme_path: Filesystem path for NVMe device for optimizer/parameter state offloading. optimizer_buffer_count: Number of buffers in buffer pool for optimizer state offloading when ``offload_optimizer_device`` is set to to ``nvme``. This should be at least the number of states maintained per parameter by the optimizer. For example, Adam optimizer has 4 states (parameter, gradient, momentum, and variance). block_size: When using NVMe Offloading, the I/O block size in bytes. queue_depth: When using NVMe Offloading, the I/O queue depth. single_submit: When using NVMe Offloading, submit requests to storage device as multiple individual requests, as opposed to one block of requests. overlap_events: When using NVMe Offloading, submit requests to storage device in an overlapped fashion without waiting for completion of earlier requests. thread_count: When using NVMe Offloading, Intra-request parallelism for each read/write submitted by a user thread. pin_memory: When using ZeRO stage 3, pin optimizer state memory on CPU. This could boost throughput at the cost of extra memory overhead. sub_group_size: When using ZeRO stage 3, defines the number of parameters within a sub group to offload at a time. Smaller numbers require more communication, but improve memory efficiency. contiguous_gradients: Copies gradients to a continuous buffer as they are produced. Avoids memory fragmentation during backwards. Useful when training large models. overlap_comm: Overlap the reduction (synchronization) of gradients with the backwards computation. This is a speed optimization when training across multiple GPUs/machines. allgather_partitions: All gather updated parameters at the end of training step, instead of using a series of broadcast collectives. reduce_scatter: Use reduce/scatter instead of allreduce to average gradients. allgather_bucket_size: Number of elements to allgather at once. Used to limit the memory required for larger model sizes, with a tradeoff with speed. reduce_bucket_size: Number of elements to reduce at once. Used to limit the memory required for larger model sizes, with a tradeoff with speed. zero_allow_untested_optimizer: Allow untested optimizers to be used with ZeRO. Currently only Adam is a DeepSpeed supported optimizer when using ZeRO. logging_batch_size_per_gpu: Config used in DeepSpeed to calculate verbose timing for logging on a per sample per second basis (only displayed if logging=logging.INFO). If set to "auto", the plugin tries to infer this from the train DataLoader's BatchSampler, else defaults to 1. To obtain accurate logs when using datasets that do not support batch samplers, set this to the actual per gpu batch size (trainer.batch_size). config: Pass in a deepspeed formatted config dict, or path to a deepspeed config: https://www.deepspeed.ai/docs/config-json. All defaults will be ignored if a config is passed in. logging_level: Set logging level for deepspeed. loss_scale: Loss scaling value for FP16 training. 0.0 results in dynamic loss scaling, otherwise static. initial_scale_power: Power of the initial dynamic loss scale value. Loss scale is computed by ``2^initial_scale_power``. loss_scale_window: Window in which to raise/lower the dynamic FP16 loss scaling value. hysteresis: FP16 Delay shift in Dynamic Loss scaling. min_loss_scale: The minimum FP16 dynamic loss scaling value. partition_activations: Enables partition activation when used with ZeRO stage 3 and model parallelism. Still requires you to wrap your forward functions in deepspeed.checkpointing.checkpoint. See `deepspeed tutorial <https://www.deepspeed.ai/tutorials/megatron/#deepspeed-activation-checkpoints-optional>`_. cpu_checkpointing: Offloads partitioned activations to CPU if ``partition_activations`` is enabled. contiguous_memory_optimization: Copies partitioned activations so that they are contiguous in memory. Not supported by all models. synchronize_checkpoint_boundary: Insert :func:`torch.cuda.synchronize` at each checkpoint boundary. load_full_weights: True when loading a single checkpoint file containing the model state dict when using ZeRO Stage 3. This differs from the DeepSpeed checkpoint which contains shards per worker. partition_module: When True, partitions the ``LightningModule`` across devices when using ZeRO Stage 3. This is the default behaviour to ensure that the entire module is appropriately initialized for DeepSpeed. When False we do not explicitly convert the model, which is fine if NO layers or ALL layers are defined in ``configure_sharded_model``. This is useful for layers such as ``torch.nn.RNN`` which do internal logic when moving to device. """ if not _DEEPSPEED_AVAILABLE: raise MisconfigurationException( "To use the DeepSpeed plugin, you must have DeepSpeed installed. pip install deepspeed" ) super().__init__( parallel_devices=parallel_devices, num_nodes=num_nodes, cluster_environment=cluster_environment, ) self.config = self._load_config(config) if self.config is None: # User has not overridden config, set defaults self.config = self._create_default_config( zero_optimization, zero_allow_untested_optimizer, logging_batch_size_per_gpu, offload_optimizer=offload_optimizer, offload_parameters=offload_parameters, nvme_path=nvme_path, offload_params_device=offload_params_device, params_buffer_count=params_buffer_count, params_buffer_size=params_buffer_size, max_in_cpu=max_in_cpu, pin_memory=pin_memory, offload_optimizer_device=offload_optimizer_device, optimizer_buffer_count=optimizer_buffer_count, block_size=block_size, queue_depth=queue_depth, single_submit=single_submit, overlap_events=overlap_events, thread_count=thread_count, partition_activations=partition_activations, cpu_checkpointing=cpu_checkpointing, contiguous_memory_optimization=contiguous_memory_optimization, synchronize_checkpoint_boundary=synchronize_checkpoint_boundary, stage=stage, contiguous_gradients=contiguous_gradients, overlap_comm=overlap_comm, allgather_partitions=allgather_partitions, reduce_scatter=reduce_scatter, allgather_bucket_size=allgather_bucket_size, reduce_bucket_size=reduce_bucket_size, sub_group_size=sub_group_size, ) self._config_initialized = False deepspeed.utils.logging.logger.setLevel(logging_level) self.remote_device = remote_device self.load_full_weights = load_full_weights self.partition_module = partition_module # default FP16 parameters. self.loss_scale = loss_scale self.initial_scale_power = initial_scale_power self.loss_scale_window = loss_scale_window self.hysteresis = hysteresis self.min_loss_scale = min_loss_scale def _load_config(self, config): if config is None and self.DEEPSPEED_ENV_VAR in os.environ: rank_zero_info(f"Loading DeepSpeed config from set {self.DEEPSPEED_ENV_VAR} environment variable") config = os.environ[self.DEEPSPEED_ENV_VAR] if isinstance(config, (str, Path)): if not os.path.isfile(config): raise MisconfigurationException( f"You passed in a path to a DeepSpeed config but the path does not exist: {config}" ) with open(config) as f: config = json.load(f) return config def setup_distributed(self): reset_seed() # determine which process we are and world size self.set_world_ranks() self._init_deepspeed_distributed() if not self._config_initialized: self._format_config() self._config_initialized = True def _init_deepspeed_distributed(self) -> None: if platform.system() != "Windows": # do not set env variables on windows, allow deepspeed to control setup self._set_node_environment_variables() log.info( "initializing deepspeed distributed: " f"GLOBAL_RANK: {self.global_rank}, " f"MEMBER: {self.global_rank + 1}/{self.world_size}" ) deepspeed.init_distributed( self.torch_distributed_backend, distributed_port=self.cluster_environment.master_port() ) def _set_node_environment_variables(self) -> None: os.environ["MASTER_ADDR"] = self.cluster_environment.master_address() os.environ["MASTER_PORT"] = str(self.cluster_environment.master_port()) os.environ["RANK"] = str(self.global_rank) os.environ["WORLD_SIZE"] = str(self.world_size) os.environ["LOCAL_RANK"] = str(self.local_rank) @property def restore_checkpoint_after_pre_dispatch(self) -> bool: return True def pre_dispatch(self): self.init_deepspeed() self.barrier() def init_deepspeed(self): accumulation_scheduler = self.lightning_module.trainer.accumulation_scheduler if accumulation_scheduler.epochs != [0]: raise MisconfigurationException( "DeepSpeed currently does not support different `accumulate_grad_batches` at different epochs." ) precision = self.lightning_module.trainer.accelerator.precision model = LightningDeepSpeedModule(pl_module=self.model, precision=precision) if self.zero_stage_3 and self.partition_module: # Ensure the entire model has been moved to the appropriate device dtype = torch.float16 if self.precision in (16, "mixed") else torch.float32 deepspeed.zero.Init( module=model, remote_device=self.remote_device, pin_memory=True, config=self.config, dtype=dtype ) if self.lightning_module.trainer and self.lightning_module.trainer.training: self._initialize_deepspeed_train(model) else: self._initialize_deepspeed_inference(model) def _init_optimizers(self) -> Tuple[Optimizer, Optional[Union[LRSchedulerTypeTuple]], Optional[int]]: optimizers, schedulers, optimizer_frequencies = self.lightning_module.trainer.init_optimizers( self.lightning_module ) if len(optimizers) > 1 or len(schedulers) > 1: raise MisconfigurationException( "DeepSpeed currently only supports single optimizer, single optional scheduler." ) return ( optimizers[0], schedulers[0] if schedulers else _get_default_scheduler_config(), optimizer_frequencies[0] if optimizer_frequencies else None, ) @property def zero_stage_3(self) -> bool: return self.config.get("zero_optimization") and self.config.get("zero_optimization").get("stage") == 3 def _initialize_deepspeed_train(self, model): if "optimizer" in self.config: optimizer, lr_scheduler = None, _get_default_scheduler_config() else: rank_zero_info( "You have not specified an optimizer or scheduler within the DeepSpeed config." "Using `configure_optimizers` to define optimizer and scheduler." ) optimizer, lr_scheduler, _ = self._init_optimizers() scheduler = lr_scheduler["scheduler"] model_parameters = filter(lambda p: p.requires_grad, self.model.parameters()) model, deepspeed_optimizer, _, deepspeed_scheduler = deepspeed.initialize( config=self.config, model=model, model_parameters=model_parameters, optimizer=optimizer, lr_scheduler=scheduler, dist_init_required=False, ) self._set_deepspeed_activation_checkpointing() # although we set these here, deepspeed manages the specific optimizer logic self.lightning_module.trainer.optimizers = [deepspeed_optimizer] deepspeed_scheduler = model.lr_scheduler if deepspeed_scheduler is not None: # disable deepspeed lr scheduling as lightning manages scheduling model.lr_scheduler = None lr_scheduler["scheduler"] = deepspeed_scheduler self.lightning_module.trainer.lr_schedulers = [lr_scheduler] self.model = model @contextlib.contextmanager def model_sharded_context(self) -> Generator[None, None, None]: if self.zero_stage_3: assert self._config_initialized dtype = torch.float16 if self.precision in (16, "mixed") else torch.float32 model_parallel_context = deepspeed.zero.Init( remote_device=self.remote_device, pin_memory=True, config=self.config, dtype=dtype ) else: model_parallel_context = super().model_sharded_context() with model_parallel_context: yield @property def precision(self) -> Union[str, int]: return self.lightning_module.trainer.precision def _set_deepspeed_activation_checkpointing(self): if self.config.get("activation_checkpointing"): checkpoint_config = self.config["activation_checkpointing"] deepspeed.checkpointing.configure( mpu_=None, partition_activations=checkpoint_config.get("partition_activations"), contiguous_checkpointing=checkpoint_config.get("contiguous_checkpointing"), checkpoint_in_cpu=checkpoint_config.get("checkpoint_in_cpu"), profile=checkpoint_config.get("profile"), ) def _initialize_deepspeed_inference(self, model): # todo: Currently DeepSpeed requires optimizers at inference to partition weights correctly optimizer, scheduler = None, None if "optimizer" not in self.config: rank_zero_info( "You have not specified an optimizer or scheduler within the DeepSpeed config." "Using `configure_optimizers` to define optimizer and scheduler." ) optimizer, lr_scheduler, _ = self._init_optimizers() scheduler = lr_scheduler["scheduler"] inference_config = { # todo: this is required for DeepSpeed throughput timers, or throughput timers will be incorrect "train_micro_batch_size_per_gpu": 1 } if "fp16" in self.config: inference_config.update({"fp16": self.config["fp16"]}) if self.zero_stage_3: inference_config.update( { "zero_allow_untested_optimizer": self.config["zero_allow_untested_optimizer"], "zero_optimization": self.config["zero_optimization"], } ) # Remove all module hooks before initializing new model remove_module_hooks(model) model, _, _, _ = deepspeed.initialize( config=inference_config, model=model, optimizer=optimizer, lr_scheduler=scheduler, model_parameters=[], dist_init_required=False, ) self.model = model @property def lightning_module(self): # the model may not be wrapped with DeepEngine & LightningDeepSpeedModule if calling this too early module = getattr(self.model, "module", self.model) return module.module if isinstance(module, LightningDeepSpeedModule) else module @property def distributed_sampler_kwargs(self): distributed_sampler_kwargs = dict(num_replicas=self.world_size, rank=self.global_rank) return distributed_sampler_kwargs def init_optimizers(self, trainer: "pl.Trainer", model: "pl.LightningModule") -> Tuple[List, List, List]: # Skip initializing optimizers here as DeepSpeed handles optimizers via config. # User may have specified config options instead in configure_optimizers, but this is handled # via `_initialize_deepspeed_train` return [], [], [] # empty optimizers, schedulers and frequencies def optimizer_step(self, optimizer: torch.optim.Optimizer, lambda_closure: Callable, **kwargs): # note: We rely on the deepspeed engine to carry out the step rather than the optimizer. # internally, the engine has a reference to the optimizer already. self.model.step(**kwargs) @property def handles_gradient_accumulation(self) -> bool: """Whether the plugin handles gradient accumulation internally.""" return True def _format_config(self): if self.config is None: raise MisconfigurationException( "To use DeepSpeed you must pass in a DeepSpeed config dict, or a path to a JSON config." " See: https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#deepspeed" ) self._format_batch_size_and_grad_accum_config() self._format_precision_config() def _format_batch_size_and_grad_accum_config(self): if "gradient_accumulation_steps" in self.config: raise MisconfigurationException( "Do not set `gradient_accumulation_steps` in the DeepSpeed config" " as this will be set with the `accumulate_grad_batches` argument passed via the Lightning Trainer." ) self.config["gradient_accumulation_steps"] = self.lightning_module.trainer.accumulate_grad_batches if "train_micro_batch_size_per_gpu" not in self.config: rank_zero_warn( "Inferring the batch size for internal deepspeed logging from the `train_dataloader()`. " "If you require skipping this, please pass " "`Trainer(plugins=DeepSpeedPlugin(logging_batch_size_per_gpu=batch_size))`" ) batch_size = self._auto_select_batch_size() self.config["train_micro_batch_size_per_gpu"] = batch_size if "gradient_clipping" not in self.config: self.config["gradient_clipping"] = self.lightning_module.trainer.gradient_clip_val def _auto_select_batch_size(self): # train_micro_batch_size_per_gpu is used for throughput logging purposes # by default we try to use the batch size of the loader batch_size = 1 if hasattr(self.lightning_module, "train_dataloader"): train_dataloader = self.lightning_module.train_dataloader() if hasattr(train_dataloader, "batch_sampler"): batch_size = train_dataloader.batch_sampler.batch_size return batch_size def _format_precision_config(self): amp_type = self.lightning_module.trainer.accelerator_connector.amp_type amp_level = self.lightning_module.trainer.accelerator_connector.amp_level precision = self.lightning_module.trainer.accelerator_connector.precision if precision in (16, "mixed"): if "fp16" not in self.config and amp_type == AMPType.NATIVE: # FP16 is a DeepSpeed standalone AMP implementation rank_zero_info("Enabling DeepSpeed FP16.") self.config["fp16"] = { "enabled": True, "loss_scale": self.loss_scale, "initial_scale_power": self.initial_scale_power, "loss_scale_window": self.loss_scale_window, "hysteresis": self.hysteresis, "min_loss_scale": self.min_loss_scale, } elif "amp" not in self.config and amp_type == AMPType.APEX: rank_zero_only("Enabling DeepSpeed APEX Implementation.") self.config["amp"] = {"enabled": True, "opt_level": amp_level} def _create_default_config( self, zero_optimization: bool, zero_allow_untested_optimizer: bool, logging_batch_size_per_gpu: Union[str, int], partition_activations: bool, cpu_checkpointing: bool, contiguous_memory_optimization: bool, synchronize_checkpoint_boundary: bool, offload_optimizer: bool, offload_parameters: bool, nvme_path: str, offload_params_device: str, params_buffer_count: int, params_buffer_size: int, max_in_cpu: int, offload_optimizer_device: str, optimizer_buffer_count: int, pin_memory: bool, block_size: int, queue_depth: int, single_submit: bool, overlap_events: bool, thread_count: int, **zero_kwargs, ) -> Dict: cfg = { "activation_checkpointing": { "partition_activations": partition_activations, "cpu_checkpointing": cpu_checkpointing, "contiguous_memory_optimization": contiguous_memory_optimization, "synchronize_checkpoint_boundary": synchronize_checkpoint_boundary, }, "aio": { "block_size": block_size, "queue_depth": queue_depth, "single_submit": single_submit, "overlap_events": overlap_events, "thread_count": thread_count, }, } if zero_optimization: zero_config = zero_kwargs if offload_optimizer: zero_config["offload_optimizer"] = { "device": offload_optimizer_device, "nvme_path": nvme_path, "buffer_count": optimizer_buffer_count, "pin_memory": pin_memory, } if offload_parameters: zero_config["offload_param"] = { "device": offload_params_device, "nvme_path": nvme_path, "buffer_count": params_buffer_count, "buffer_size": params_buffer_size, "max_in_cpu": max_in_cpu, "pin_memory": pin_memory, } cfg = { "zero_allow_untested_optimizer": zero_allow_untested_optimizer, "zero_optimization": zero_config, **cfg, } if logging_batch_size_per_gpu != "auto": cfg = {"train_micro_batch_size_per_gpu": logging_batch_size_per_gpu, **cfg} return cfg @property def deepspeed_engine(self):
@property def _multi_device(self) -> bool: return self.num_processes > 1 or self.num_nodes > 1 def save_checkpoint(self, checkpoint: Dict, filepath: _PATH) -> None: """Save model/training states as a checkpoint file through state-dump and file-write. Args: checkpoint: The checkpoint state dictionary filepath: write-target file's path """ if self.zero_stage_3 and self._multi_device and self.is_global_zero: warning_cache.warn( "When saving the DeepSpeed Stage 3 checkpoint, " "each worker will save a shard of the checkpoint within a directory. " "If a single file is required after training, " "see https://pytorch-lightning.readthedocs.io/en/latest/advanced/advanced_gpu.html#" "deepspeed-zero-stage-3-single-file for instructions." ) # Use deepspeed's internal checkpointing function to handle partitioned weights across processes # dump states as a checkpoint dictionary object _exclude_keys = ["state_dict", "optimizer_states", "lr_schedulers"] checkpoint = {k: v for k, v in checkpoint.items() if k not in _exclude_keys} self.deepspeed_engine.save_checkpoint(filepath, client_state=checkpoint) def load_checkpoint(self, checkpoint_path: _PATH) -> Dict[str, Any]: if self.load_full_weights and self.zero_stage_3: # Broadcast to ensure we load from the rank 0 checkpoint # This doesn't have to be the case when using deepspeed sharded checkpointing checkpoint_path = self.broadcast(checkpoint_path) return super().load_checkpoint(checkpoint_path) # Rely on deepspeed to load the checkpoint and necessary information from pytorch_lightning.trainer.states import TrainerFn is_fitting = self.lightning_module.trainer.state.fn == TrainerFn.FITTING _, client_state = self.deepspeed_engine.load_checkpoint( checkpoint_path, load_optimizer_states=is_fitting, load_lr_scheduler_states=is_fitting ) if client_state is None: raise MisconfigurationException( "DeepSpeed was unable to load the checkpoint. Ensure you passed in a DeepSpeed compatible checkpoint " "or a single checkpoint file with `Trainer(plugins=DeepSpeedPlugin(load_full_weights=True))`." ) return client_state @property def lightning_restore_optimizer_and_schedulers(self) -> bool: # managed by DeepSpeed if self.load_full_weights and self.zero_stage_3 and self.lightning_module.trainer.state.fn == TrainerFn.FITTING: rank_zero_warn( "A single checkpoint file has been given. This means optimizer states and " "scheduler states can not be restored. If you'd like to restore these states, you must " "provide a path to the originally saved DeepSpeed checkpoint." ) return False def load_model_state_dict(self, checkpoint: Mapping[str, Any]) -> None: # override to do nothing, deepspeed engine already loaded the weights in `load_checkpoint()` if self.load_full_weights and self.zero_stage_3: self.model_to_device() self._restore_zero_state(checkpoint) def _restore_zero_state(self, ckpt: Mapping[str, Any]) -> None: """Overrides the normal load_state_dict behaviour in PyTorch to ensure we gather parameters that may be sharded across processes before loading the state dictionary when using ZeRO stage 3. This is then automatically synced across processes. Args: ckpt: The ckpt file. """ def load(module: torch.nn.Module, prefix=""): missing_keys = [] unexpected_keys = [] error_msgs = [] state_dict = ckpt["state_dict"] # copy state_dict so _load_from_state_dict can modify it metadata = getattr(state_dict, "_metadata", None) state_dict = state_dict.copy() if metadata is not None: state_dict._metadata = metadata local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {}) # because zero3 puts placeholders in model params, this context # manager gathers (unpartitions) the params of the current layer, then loads from # the state dict and then re-partitions them again with deepspeed.zero.GatheredParameters(list(module.parameters(recurse=False)), modifier_rank=0): if self.is_global_zero: module._load_from_state_dict( state_dict=state_dict, prefix=prefix, local_metadata=local_metadata, strict=True, missing_keys=missing_keys, unexpected_keys=unexpected_keys, error_msgs=error_msgs, ) for name, child in module._modules.items(): if child is not None: load(child, prefix + name + ".") load(self.lightning_module, prefix="") def load_optimizer_state_dict(self, checkpoint: Mapping[str, Any]) -> None: # override to do nothing, deepspeed engine already loaded the states in `load_checkpoint()` pass @classmethod def register_plugins(cls, plugin_registry: Dict) -> None: plugin_registry.register("deepspeed", cls, description="Default DeepSpeed Plugin") plugin_registry.register("deepspeed_stage_1", cls, description="DeepSpeed with ZeRO Stage 1 enabled", stage=1) plugin_registry.register("deepspeed_stage_2", cls, description="DeepSpeed with ZeRO Stage 2 enabled", stage=2) plugin_registry.register( "deepspeed_stage_2_offload", cls, description="DeepSpeed ZeRO Stage 2 and CPU Offload", stage=2, offload_optimizer=True, ) plugin_registry.register("deepspeed_stage_3", cls, description="DeepSpeed ZeRO Stage 3", stage=3) plugin_registry.register( "deepspeed_stage_3_offload", cls, description="DeepSpeed ZeRO Stage 3 and CPU Offload", stage=3, offload_optimizer=True, offload_parameters=True, ) plugin_registry.register( "deepspeed_stage_3_offload_nvme", cls, description="DeepSpeed ZeRO Stage 3 and NVMe Offload", stage=3, offload_optimizer=True, offload_parameters=True, remote_device="nvme", offload_params_device="nvme", offload_optimizer_device="nvme", ) @property def checkpoint_io(self) -> CheckpointIO: return self._checkpoint_io @checkpoint_io.setter def checkpoint_io(self, plugin: CheckpointIO) -> None: raise MisconfigurationException("DeepSpeed currently does not support custom checkpoint plugins.") def validation_step(self, *args, **kwargs): return self.model(*args, **kwargs) def test_step(self, *args, **kwargs): return self.model(*args, **kwargs) def predict_step(self, *args, **kwargs): return self.model(*args, **kwargs)
return self.model
coco.rs
use std::fs::OpenOptions; use std::{env, path::Path, process::exit}; use structopt::StructOpt; use coco::app::analysis; use coco::app::plugin_helper::PluginHelper; use coco::app::PluginManager; use coco::domain::{CocoCommand, CocoOpt}; use core_model::CocoConfig; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); fn main() { let opt: CocoOpt = CocoOpt::from_args(); if let Some(sub_cmd) = opt.cmd { match sub_cmd { CocoCommand::Init => { create_config_file(); exit(0); } CocoCommand::Plugins => { let plugins_path = Path::new("coco_plugins"); PluginHelper::setup(&plugins_path, VERSION); exit(0); } } } let config_file = &opt.config_file; let config = CocoConfig::from_file(config_file); let is_debug = opt.debug; if is_debug { println!("found config file: {}", config_file); println!("{:?}", opt); } let analyst = analysis::Analyst::from(&config); analyst.analysis(opt); let plugin_manager = PluginManager::from(&config); plugin_manager.run_all(is_debug); } fn create_config_file() { println!("creating coco.yml"); match OpenOptions::new() .write(true) .create_new(true) .open("coco.yml") .map(|file| serde_yaml::to_writer(file, &CocoConfig::default()).unwrap()) { Ok(_) => println!("success created"), Err(e) => println!("coco.yml create failed: {}", e), }
use std::env; use core_model::CocoConfig; #[test] fn should_set_default_config() { let config = CocoConfig::from_file(""); let current = env::current_dir().unwrap(); let url = current.into_os_string().to_str().unwrap().to_string(); assert_eq!(config.repos.len(), 1); assert_eq!(url, config.repos[0].url); assert!(config.plugins.is_none()) } }
} #[cfg(test)] mod test {
sqlite3_test.go
// SPDX-License-Identifier: MIT package dialect_test import ( "testing" "github.com/issue9/assert/v2" "github.com/issue9/orm/v4/core" "github.com/issue9/orm/v4/dialect" "github.com/issue9/orm/v4/internal/sqltest" "github.com/issue9/orm/v4/internal/test" "github.com/issue9/orm/v4/sqlbuilder" ) // 创建测试数据表的脚本 var sqlite3CreateTable = []string{`CREATE TABLE fk_table( id integer NOT NULL, name text not null, address text not null, constraint fk_table_pk PRIMARY KEY(id) )`, `CREATE TABLE usr ( id integer NOT NULL, created integer NOT NULL, nickname text NOT NULL, state integer NOT NULL, username text NOT NULL, mobile text NOT NULL, email text NOT NULL, pwd text NOT NULL, CONSTRAINT usr_pk PRIMARY KEY (id), CONSTRAINT u_user_xx1 UNIQUE (mobile,username), CONSTRAINT u_user_email1 UNIQUE (email,username), CONSTRAINT unique_id UNIQUE (id), CONSTRAINT xxx_fk FOREIGN KEY (id) REFERENCES fk_table (id), CONSTRAINT xxx CHECK (created > 0) )`, `create index index_user_mobile on usr(mobile)`, `create unique index index_user_unique_email_id on usr(email,id)`, } func clearSqlite3CreateTable(t *test.Driver, db core.Engine) { _, err := db.Exec
ersionSQL(t *testing.T) { a := assert.New(t, false) suite := test.NewSuite(a, test.Sqlite3) defer suite.Close() suite.ForEach(func(t *test.Driver) { testDialectVersionSQL(t) }) } func TestSqlite3_AddConstraintStmtHook(t *testing.T) { a := assert.New(t, false) suite := test.NewSuite(a, test.Sqlite3) defer suite.Close() suite.ForEach(func(t *test.Driver) { db := t.DB for _, query := range sqlite3CreateTable { _, err := db.Exec(query) t.NotError(err) } defer clearSqlite3CreateTable(t, db) // check 约束 err := sqlbuilder.AddConstraint(db). Table("fk_table"). Check("id_great_zero", "id>0"). Exec() t.NotError(err) }) } func TestSqlite3_DropConstraintStmtHook(t *testing.T) { a := assert.New(t, false) suite := test.NewSuite(a, test.Sqlite3) defer suite.Close() suite.ForEach(func(t *test.Driver) { db := t.DB for _, query := range sqlite3CreateTable { _, err := db.Exec(query) t.NotError(err) } defer clearSqlite3CreateTable(t, db) testDialectDropConstraintStmtHook(t) }) } func TestSqlite3_DropColumnStmtHook(t *testing.T) { a := assert.New(t, false) suite := test.NewSuite(a, test.Sqlite3) defer suite.Close() suite.ForEach(func(t *test.Driver) { db := t.DB for _, query := range sqlite3CreateTable { _, err := db.Exec(query) t.NotError(err) } defer clearSqlite3CreateTable(t, db) err := sqlbuilder.DropColumn(db). Table("usr"). Column("state"). Exec() t.NotError(err) // 查询删除的列会出错 _, err = db.Query("SELECT state FROM usr") t.Error(err) }) } func TestSqlite3_CreateTableOptions(t *testing.T) { a := assert.New(t, false) builder := core.NewBuilder("") a.NotNil(builder) var s = dialect.Sqlite3("sqlite3_driver", "") // 空的 meta a.NotError(s.CreateTableOptionsSQL(builder, nil)) a.Equal(builder.Len(), 0) // engine builder.Reset() a.NotError(s.CreateTableOptionsSQL(builder, map[string][]string{ "sqlite3_rowid": {"false"}, })) a.True(builder.Len() > 0) query, err := builder.String() a.NotError(err) sqltest.Equal(a, query, "without rowid") builder.Reset() a.Error(s.CreateTableOptionsSQL(builder, map[string][]string{ "sqlite3_rowid": {"false", "false"}, })) } func TestSqlite3_TruncateTableSQL(t *testing.T) { a := assert.New(t, false) suite := test.NewSuite(a, test.Sqlite3) defer suite.Close() suite.ForEach(func(t *test.Driver) { qs, err := t.DB.Dialect().TruncateTableSQL("tbl", "") a.NotError(err).Equal(1, len(qs)) sqltest.Equal(a, qs[0], "DELETE FROM {tbl}") qs, err = t.DB.Dialect().TruncateTableSQL("tbl", "id") a.NotError(err).Equal(2, len(qs)) sqltest.Equal(a, qs[0], "DELETE FROM {tbl}") sqltest.Equal(a, qs[1], "DELETE FROM SQLITE_SEQUENCE WHERE name='tbl'") }) } func TestSqlite3_SQLType(t *testing.T) { a := assert.New(t, false) var data = []*sqlTypeTester{ { // col == nil err: true, }, { // col.PrimitiveType == nil col: &core.Column{PrimitiveType: core.Auto}, err: true, }, { col: &core.Column{PrimitiveType: core.Int}, SQLType: "INTEGER NOT NULL", }, { col: &core.Column{PrimitiveType: core.Bool}, SQLType: "INTEGER NOT NULL", }, { col: &core.Column{PrimitiveType: core.Bool}, SQLType: "INTEGER NOT NULL", }, { col: &core.Column{PrimitiveType: core.Bytes}, SQLType: "BLOB NOT NULL", }, { col: &core.Column{PrimitiveType: core.Int64}, SQLType: "INTEGER NOT NULL", }, { col: &core.Column{PrimitiveType: core.Float64}, SQLType: "REAL NOT NULL", }, { col: &core.Column{PrimitiveType: core.String}, SQLType: "TEXT NOT NULL", }, { col: &core.Column{PrimitiveType: core.Decimal}, SQLType: "NUMERIC NOT NULL", }, { col: &core.Column{ PrimitiveType: core.String, Nullable: true, }, SQLType: "TEXT", }, { col: &core.Column{ PrimitiveType: core.String, Default: "123", }, SQLType: "TEXT NOT NULL", }, { col: &core.Column{ PrimitiveType: core.String, Default: "123", HasDefault: true, }, SQLType: "TEXT NOT NULL DEFAULT '123'", }, { col: &core.Column{ PrimitiveType: core.Int, Length: []int{5, 6}, }, SQLType: "INTEGER NOT NULL", }, { col: &core.Column{ PrimitiveType: core.Int, AI: true, }, SQLType: "INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL", }, { col: &core.Column{PrimitiveType: core.String}, SQLType: "TEXT NOT NULL", }, { col: &core.Column{PrimitiveType: core.Float64}, SQLType: "REAL NOT NULL", }, { col: &core.Column{PrimitiveType: core.Int64}, SQLType: "INTEGER NOT NULL", }, { col: &core.Column{PrimitiveType: core.Time}, SQLType: "TIMESTAMP NOT NULL", }, } testSQLType(a, dialect.Sqlite3("sqlite3_driver", ""), data) } func TestSqlite3_Types(t *testing.T) { a := assert.New(t, false) suite := test.NewSuite(a, test.Sqlite3) defer suite.Close() suite.ForEach(func(t *test.Driver) { testTypes(t) }) } func TestSqlite3_TypesDefault(t *testing.T) { a := assert.New(t, false) suite := test.NewSuite(a, test.Sqlite3) defer suite.Close() suite.ForEach(func(t *test.Driver) { testTypesDefault(t) }) }
("DROP TABLE `usr`") t.NotError(err) _, err = db.Exec("DROP TABLE `fk_table`") t.NotError(err) } func TestSqlite3_V
plugin.go
// Copyright (c) 2019 Cisco and/or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package configurator import ( "go.ligato.io/cn-infra/v2/infra" "go.ligato.io/cn-infra/v2/rpc/grpc" "go.ligato.io/cn-infra/v2/servicelabel" "go.ligato.io/vpp-agent/v3/plugins/govppmux" iflinuxplugin "go.ligato.io/vpp-agent/v3/plugins/linux/ifplugin" iflinuxcalls "go.ligato.io/vpp-agent/v3/plugins/linux/ifplugin/linuxcalls" l3linuxcalls "go.ligato.io/vpp-agent/v3/plugins/linux/l3plugin/linuxcalls" "go.ligato.io/vpp-agent/v3/plugins/linux/nsplugin" "go.ligato.io/vpp-agent/v3/plugins/netalloc" "go.ligato.io/vpp-agent/v3/plugins/orchestrator" abfvppcalls "go.ligato.io/vpp-agent/v3/plugins/vpp/abfplugin/vppcalls" "go.ligato.io/vpp-agent/v3/plugins/vpp/aclplugin" aclvppcalls "go.ligato.io/vpp-agent/v3/plugins/vpp/aclplugin/vppcalls" "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin" ifvppcalls "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/vppcalls" ipsecvppcalls "go.ligato.io/vpp-agent/v3/plugins/vpp/ipsecplugin/vppcalls" "go.ligato.io/vpp-agent/v3/plugins/vpp/l2plugin" l2vppcalls "go.ligato.io/vpp-agent/v3/plugins/vpp/l2plugin/vppcalls" "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin" l3vppcalls "go.ligato.io/vpp-agent/v3/plugins/vpp/l3plugin/vppcalls" natvppcalls "go.ligato.io/vpp-agent/v3/plugins/vpp/natplugin/vppcalls" puntvppcalls "go.ligato.io/vpp-agent/v3/plugins/vpp/puntplugin/vppcalls" rpc "go.ligato.io/vpp-agent/v3/proto/ligato/configurator" "go.ligato.io/vpp-agent/v3/proto/ligato/vpp" ) // Default Go routine count for linux configuration retrieval const defaultGoRoutineCount = 10 // Plugin registers VPP GRPC services in *grpc.Server. type Plugin struct { Deps configurator configuratorServer } // Deps - dependencies of Plugin type Deps struct { infra.PluginDeps GRPCServer grpc.Server Dispatch orchestrator.Dispatcher VPP govppmux.API ServiceLabel servicelabel.ReaderAPI AddrAlloc netalloc.AddressAllocator VPPACLPlugin aclplugin.API VPPIfPlugin ifplugin.API VPPL2Plugin *l2plugin.L2Plugin VPPL3Plugin l3plugin.API LinuxIfPlugin iflinuxplugin.API NsPlugin nsplugin.API } // Init sets plugin child loggers func (p *Plugin) Init() error { p.configurator.log = p.Log.NewLogger("configurator") p.configurator.dumpService.log = p.Log.NewLogger("dump") p.configurator.notifyService.log = p.Log.NewLogger("notify") p.configurator.dispatch = p.Dispatch if err := p.initHandlers(); err != nil { return err }
grpcServer := p.GRPCServer.GetServer() if grpcServer != nil { rpc.RegisterConfiguratorServiceServer(grpcServer, &p.configurator) } if p.VPPIfPlugin != nil { p.VPPIfPlugin.SetNotifyService(p.sendVppNotification) } return nil } func (p *Plugin) sendVppNotification(vppNotification *vpp.Notification) { p.configurator.notifyService.pushNotification(&rpc.Notification{ Notification: &rpc.Notification_VppNotification{ VppNotification: vppNotification, }, }) } // Close does nothing. func (p *Plugin) Close() error { return nil } // helper method initializes all VPP/Linux plugin handlers func (p *Plugin) initHandlers() (err error) { // VPP Indexes ifIndexes := p.VPPIfPlugin.GetInterfaceIndex() dhcpIndexes := p.VPPIfPlugin.GetDHCPIndex() bdIndexes := p.VPPL2Plugin.GetBDIndex() aclIndexes := p.VPPACLPlugin.GetACLIndex() // TODO: make ACL optional vrfIndexes := p.VPPL3Plugin.GetVRFIndex() // Linux Indexes linuxIfIndexes := p.LinuxIfPlugin.GetInterfaceIndex() // VPP handlers p.configurator.ifHandler = ifvppcalls.CompatibleInterfaceVppHandler(p.VPP, p.Log) if p.configurator.ifHandler == nil { p.Log.Info("VPP Interface handler is not available, it will be skipped") } p.configurator.l2Handler = l2vppcalls.CompatibleL2VppHandler(p.VPP, ifIndexes, bdIndexes, p.Log) if p.configurator.l2Handler == nil { p.Log.Info("VPP L2 handler is not available, it will be skipped") } p.configurator.l3Handler = l3vppcalls.CompatibleL3VppHandler(p.VPP, ifIndexes, vrfIndexes, p.AddrAlloc, p.Log) if p.configurator.l3Handler == nil { p.Log.Info("VPP L3 handler is not available, it will be skipped") } p.configurator.ipsecHandler = ipsecvppcalls.CompatibleIPSecVppHandler(p.VPP, ifIndexes, p.Log) if p.configurator.ipsecHandler == nil { p.Log.Info("VPP IPSec handler is not available, it will be skipped") } // plugins p.configurator.abfHandler = abfvppcalls.CompatibleABFHandler(p.VPP, aclIndexes, ifIndexes, p.Log) if p.configurator.abfHandler == nil { p.Log.Info("VPP ABF handler is not available, it will be skipped") } p.configurator.aclHandler = aclvppcalls.CompatibleACLHandler(p.VPP, ifIndexes) if p.configurator.aclHandler == nil { p.Log.Info("VPP ACL handler is not available, it will be skipped") } p.configurator.natHandler = natvppcalls.CompatibleNatVppHandler(p.VPP, ifIndexes, dhcpIndexes, p.Log) if p.configurator.natHandler == nil { p.Log.Info("VPP NAT handler is not available, it will be skipped") } p.configurator.puntHandler = puntvppcalls.CompatiblePuntVppHandler(p.VPP, ifIndexes, p.Log) if p.configurator.puntHandler == nil { p.Log.Info("VPP Punt handler is not available, it will be skipped") } // Linux handlers p.configurator.linuxIfHandler = iflinuxcalls.NewNetLinkHandler(p.NsPlugin, linuxIfIndexes, p.ServiceLabel.GetAgentPrefix(), defaultGoRoutineCount, p.Log) p.configurator.linuxL3Handler = l3linuxcalls.NewNetLinkHandler(p.NsPlugin, linuxIfIndexes, defaultGoRoutineCount, p.Log) return nil }
propertyNamesWithStringLiteral.ts
class
{ a: number; r: number; g: number; b: number; } interface NamedColors { azure: _Color; "blue": _Color; "pale blue": _Color; } module Color { export var namedColors: NamedColors; } var a = Color.namedColors["azure"]; var a = Color.namedColors.blue; // Should not error var a = Color.namedColors["pale blue"]; // should not error
_Color
eap_socket.py
"""Handle the EAP socket""" from __future__ import absolute_import import struct from abc import ABC, abstractmethod from fcntl import ioctl import errno import socket from mac_address import MacAddress from utils import get_logger, get_interface_mac class PromiscuousSocket(ABC): """Abstract Raw Socket in Promiscuous Mode""" SIOCGIFINDEX = 0x8933 PACKET_MR_PROMISC = 1 SOL_PACKET = 263 PACKET_ADD_MEMBERSHIP = 1 @abstractmethod def send(self, data): # pylint: disable=missing-docstring pass @abstractmethod def receive(self): # pylint: disable=missing-docstring pass @abstractmethod def setup(self): # pylint: disable=missing-docstring pass def __init__(self, interface_name, log_prefix): self.socket = None self.interface_index = None self.interface_name = interface_name self.logger = get_logger(log_prefix) self.eap_address = MacAddress.from_string(get_interface_mac(interface_name)) def _setup(self, socket_filter): """Set up the socket""" self.logger.debug("Setting up socket on interface: %s", self.interface_name) try: self.open(socket_filter) self.get_interface_index() self.set_interface_promiscuous() except socket.error as err: self.logger.error("Unable to setup socket: %s", str(err)) raise err def open(self, socket_filter): """Setup EAP socket""" self.socket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket_filter)
"""Get the interface index of the EAP Socket""" # http://man7.org/linux/man-pages/man7/netdevice.7.html request = struct.pack('16sI', self.interface_name.encode("utf-8"), 0) response = ioctl(self.socket, self.SIOCGIFINDEX, request) _ifname, self.interface_index = struct.unpack('16sI', response) def set_interface_promiscuous(self): """Sets the EAP interface to be able to receive EAP messages""" request = struct.pack("IHH8s", self.interface_index, self.PACKET_MR_PROMISC, len(self.eap_address.address), self.eap_address.address) self.socket.setsockopt(self.SOL_PACKET, self.PACKET_ADD_MEMBERSHIP, request) def shutdown(self): """Shutdown socket""" self.socket.close() class EapSocket(PromiscuousSocket): """Handle the EAP socket""" def setup(self): """Set up the socket""" self._setup(socket.htons(0x888e)) self.socket.settimeout(2.0) def send(self, data): """send on eap socket. data (bytes): data to send""" self.socket.send(data) def receive(self): """receive from eap socket""" # While socket hasn't been closed while self.socket.fileno() != -1: try: return self.socket.recv(4096) except socket.timeout: # Socket timed out. Expected. Move on. continue except OSError as exception: # socket closed if exception.errno == errno.EBADFD: break except Exception: raise
self.socket.bind((self.interface_name, 0)) def get_interface_index(self):
model_check.py
# See LICENSE for licensing information. # # Copyright (c) 2016-2021 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # import sys,re,shutil import debug import tech import math from .stimuli import * from .trim_spice import * from .charutils import * import utils from globals import OPTS from .delay import delay from .measurements import * class model_check(delay): """Functions to test for the worst case delay in a target SRAM The current worst case determines a feasible period for the SRAM then tests several bits and record the delay and differences between the bits. """ def __init__(self, sram, spfile, corner, custom_delaychain=False): super().__init__(sram, spfile, corner) self.period = tech.spice["feasible_period"] self.create_data_names() self.custom_delaychain=custom_delaychain def create_data_names(self): self.wl_meas_name, self.wl_model_name = "wl_measures", "wl_model" self.sae_meas_name, self.sae_model_name = "sae_measures", "sae_model" self.wl_slew_name, self.sae_slew_name = "wl_slews", "sae_slews" self.bl_meas_name, self.bl_slew_name = "bl_measures", "bl_slews" self.power_name = "total_power" def create_measurement_names(self, port): """Create measurement names. The names themselves currently define the type of measurement""" #Create delay measurement names wl_en_driver_delay_names = ["delay_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())] wl_driver_delay_names = ["delay_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())] sen_driver_delay_names = ["delay_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())] if self.custom_delaychain: dc_delay_names = ['delay_dc_out_final'] else: dc_delay_names = ["delay_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)] self.wl_delay_meas_names = wl_en_driver_delay_names+["delay_wl_en", "delay_wl_bar"]+wl_driver_delay_names+["delay_wl"] if port not in self.sram.readonly_ports: self.rbl_delay_meas_names = ["delay_gated_clk_nand", "delay_delay_chain_in"]+dc_delay_names else: self.rbl_delay_meas_names = ["delay_gated_clk_nand"]+dc_delay_names self.sae_delay_meas_names = ["delay_pre_sen"]+sen_driver_delay_names+["delay_sen"] # if self.custom_delaychain: # self.delay_chain_indices = (len(self.rbl_delay_meas_names), len(self.rbl_delay_meas_names)+1) # else: self.delay_chain_indices = (len(self.rbl_delay_meas_names)-len(dc_delay_names), len(self.rbl_delay_meas_names)) #Create slew measurement names wl_en_driver_slew_names = ["slew_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())] wl_driver_slew_names = ["slew_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())] sen_driver_slew_names = ["slew_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())] if self.custom_delaychain: dc_slew_names = ['slew_dc_out_final'] else: dc_slew_names = ["slew_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)] self.wl_slew_meas_names = ["slew_wl_gated_clk_bar"]+wl_en_driver_slew_names+["slew_wl_en", "slew_wl_bar"]+wl_driver_slew_names+["slew_wl"] if port not in self.sram.readonly_ports: self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar","slew_gated_clk_nand", "slew_delay_chain_in"]+dc_slew_names else: self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar"]+dc_slew_names self.sae_slew_meas_names = ["slew_replica_bl0", "slew_pre_sen"]+sen_driver_slew_names+["slew_sen"] self.bitline_meas_names = ["delay_wl_to_bl", "delay_bl_to_dout"] self.power_meas_names = ['read0_power'] def create_signal_names(self, port): """Creates list of the signal names used in the spice file along the wl and sen paths. Names are re-harded coded here; i.e. the names are hardcoded in most of OpenRAM and are replicated here. """ delay.create_signal_names(self) #Signal names are all hardcoded, need to update to make it work for probe address and different configurations. wl_en_driver_signals = ["Xsram.Xcontrol{}.Xbuf_wl_en.Zb{}_int".format('{}', stage) for stage in range(1,self.get_num_wl_en_driver_stages())] wl_driver_signals = ["Xsram.Xbank0.Xwordline_driver{}.Xwl_driver_inv{}.Zb{}_int".format('{}', self.wordline_row, stage) for stage in range(1,self.get_num_wl_driver_stages())] sen_driver_signals = ["Xsram.Xcontrol{}.Xbuf_s_en.Zb{}_int".format('{}',stage) for stage in range(1,self.get_num_sen_driver_stages())] if self.custom_delaychain: delay_chain_signal_names = [] else: delay_chain_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.Xdelay_chain.dout_{}".format('{}', stage) for stage in range(1,self.get_num_delay_stages())] if len(self.sram.all_ports) > 1: port_format = '{}' else: port_format = '' self.wl_signal_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')]+\ wl_en_driver_signals+\ ["Xsram.wl_en{}".format('{}'), "Xsram.Xbank0.Xwordline_driver{}.wl_bar_{}".format('{}',self.wordline_row)]+\ wl_driver_signals+\ ["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row)] pre_delay_chain_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')] if port not in self.sram.readonly_ports: pre_delay_chain_names+= ["Xsram.Xcontrol{}.Xand2_rbl_in.zb_int".format('{}'), "Xsram.Xcontrol{}.rbl_in".format('{}')] self.rbl_en_signal_names = pre_delay_chain_names+\ delay_chain_signal_names+\ ["Xsram.Xcontrol{}.Xreplica_bitline.delayed_en".format('{}')] self.sae_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.bl0_0".format('{}'), "Xsram.Xcontrol{}.pre_s_en".format('{}')]+\ sen_driver_signals+\ ["Xsram.s_en{}".format('{}')] dout_name = "{0}{1}_{2}".format(self.dout_name,"{}",self.probe_data) #Empty values are the port and probe data bit self.bl_signal_names = ["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row),\ "Xsram.Xbank0.bl{}_{}".format(port_format, self.bitline_column),\ dout_name] def create_measurement_objects(self): """Create the measurements used for read and write ports""" self.create_wordline_meas_objs() self.create_sae_meas_objs() self.create_bl_meas_objs() self.create_power_meas_objs() self.all_measures = self.wl_meas_objs+self.sae_meas_objs+self.bl_meas_objs+self.power_meas_objs def create_power_meas_objs(self): """Create power measurement object. Only one.""" self.power_meas_objs = [] self.power_meas_objs.append(power_measure(self.power_meas_names[0], "FALL", measure_scale=1e3)) def create_wordline_meas_objs(self): """Create the measurements to measure the wordline path from the gated_clk_bar signal""" self.wl_meas_objs = [] trig_dir = "RISE" targ_dir = "FALL" for i in range(1, len(self.wl_signal_names)): self.wl_meas_objs.append(delay_measure(self.wl_delay_meas_names[i-1], self.wl_signal_names[i-1], self.wl_signal_names[i], trig_dir, targ_dir, measure_scale=1e9)) self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[i-1], self.wl_signal_names[i-1], trig_dir, measure_scale=1e9)) temp_dir = trig_dir trig_dir = targ_dir targ_dir = temp_dir self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[-1], self.wl_signal_names[-1], trig_dir, measure_scale=1e9)) def create_bl_meas_objs(self): """Create the measurements to measure the bitline to dout, static stages""" #Bitline has slightly different measurements, objects appends hardcoded. self.bl_meas_objs = [] trig_dir, targ_dir = "RISE", "FALL" #Only check read 0 self.bl_meas_objs.append(delay_measure(self.bitline_meas_names[0], self.bl_signal_names[0], self.bl_signal_names[-1], trig_dir, targ_dir, measure_scale=1e9)) def create_sae_meas_objs(self): """Create the measurements to measure the sense amp enable path from the gated_clk_bar signal. The RBL splits this path into two.""" self.sae_meas_objs = [] trig_dir = "RISE" targ_dir = "FALL" #Add measurements from gated_clk_bar to RBL for i in range(1, len(self.rbl_en_signal_names)): self.sae_meas_objs.append(delay_measure(self.rbl_delay_meas_names[i-1], self.rbl_en_signal_names[i-1], self.rbl_en_signal_names[i], trig_dir, targ_dir, measure_scale=1e9)) self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[i-1], self.rbl_en_signal_names[i-1], trig_dir, measure_scale=1e9)) temp_dir = trig_dir trig_dir = targ_dir targ_dir = temp_dir if self.custom_delaychain: #Hack for custom delay chains self.sae_meas_objs[-2] = delay_measure(self.rbl_delay_meas_names[-1], self.rbl_en_signal_names[-2], self.rbl_en_signal_names[-1], "RISE", "RISE", measure_scale=1e9) self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[-1], self.rbl_en_signal_names[-1], trig_dir, measure_scale=1e9)) #Add measurements from rbl_out to sae. Trigger directions do not invert from previous stage due to RBL. trig_dir = "FALL" targ_dir = "RISE" for i in range(1, len(self.sae_signal_names)): self.sae_meas_objs.append(delay_measure(self.sae_delay_meas_names[i-1], self.sae_signal_names[i-1], self.sae_signal_names[i], trig_dir, targ_dir, measure_scale=1e9)) self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[i-1], self.sae_signal_names[i-1], trig_dir, measure_scale=1e9)) temp_dir = trig_dir trig_dir = targ_dir targ_dir = temp_dir self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[-1], self.sae_signal_names[-1], trig_dir, measure_scale=1e9)) def write_delay_measures(self): """ Write the measure statements to quantify the delay and power results for all targeted ports. """ self.sf.write("\n* Measure statements for delay and power\n") # Output some comments to aid where cycles start and what is happening for comment in self.cycle_comments: self.sf.write("* {}\n".format(comment)) for read_port in self.targ_read_ports: self.write_measures_read_port(read_port) def get_delay_measure_variants(self, port, measure_obj): """Get the measurement values that can either vary from simulation to simulation (vdd, address) or port to port (time delays)""" #Return value is intended to match the delay measure format: trig_td, targ_td, vdd, port #Assuming only read 0 for now debug.info(3,"Power measurement={}".format(measure_obj)) if (type(measure_obj) is delay_measure or type(measure_obj) is slew_measure): meas_cycle_delay = self.cycle_times[self.measure_cycles[port]["read0"]] + self.period/2 return (meas_cycle_delay, meas_cycle_delay, self.vdd_voltage, port) elif type(measure_obj) is power_measure: return self.get_power_measure_variants(port, measure_obj, "read") else: debug.error("Measurement not recognized by the model checker.",1) def get_power_measure_variants(self, port, power_obj, operation): """Get the measurement values that can either vary port to port (time delays)""" #Return value is intended to match the power measure format: t_initial, t_final, port t_initial = self.cycle_times[self.measure_cycles[port]["read0"]] t_final = self.cycle_times[self.measure_cycles[port]["read0"]+1] return (t_initial, t_final, port) def write_measures_read_port(self, port): """ Write the measure statements for all nodes along the wordline path. """ # add measure statements for delays/slews for measure in self.all_measures: measure_variant_inp_tuple = self.get_delay_measure_variants(port, measure) measure.write_measure(self.stim, measure_variant_inp_tuple) def get_measurement_values(self, meas_objs, port): """Gets the delays and slews from a specified port from the spice output file and returns them as lists.""" delay_meas_list = [] slew_meas_list = [] power_meas_list=[] for measure in meas_objs: measure_value = measure.retrieve_measure(port=port) if type(measure_value) != float: debug.error("Failed to Measure Value:\n\t\t{}={}".format(measure.name, measure_value),1) if type(measure) is delay_measure: delay_meas_list.append(measure_value) elif type(measure)is slew_measure: slew_meas_list.append(measure_value) elif type(measure)is power_measure: power_meas_list.append(measure_value) else: debug.error("Measurement object not recognized.",1) return delay_meas_list, slew_meas_list,power_meas_list def run_delay_simulation(self): """ This tries to simulate a period and checks if the result works. If so, it returns True and the delays, slews, and powers. It works on the trimmed netlist by default, so powers do not include leakage of all cells. """ #Sanity Check debug.check(self.period > 0, "Target simulation period non-positive") wl_delay_result = [[] for i in self.all_ports] wl_slew_result = [[] for i in self.all_ports] sae_delay_result = [[] for i in self.all_ports] sae_slew_result = [[] for i in self.all_ports] bl_delay_result = [[] for i in self.all_ports] bl_slew_result = [[] for i in self.all_ports] power_result = [[] for i in self.all_ports] # Checking from not data_value to data_value self.write_delay_stimulus() self.stim.run_sim() #running sim prodoces spice output file. #Retrieve the results from the output file for port in self.targ_read_ports: #Parse and check the voltage measurements wl_delay_result[port], wl_slew_result[port],_ = self.get_measurement_values(self.wl_meas_objs, port) sae_delay_result[port], sae_slew_result[port],_ = self.get_measurement_values(self.sae_meas_objs, port) bl_delay_result[port], bl_slew_result[port],_ = self.get_measurement_values(self.bl_meas_objs, port) _,__,power_result[port] = self.get_measurement_values(self.power_meas_objs, port) return (True,wl_delay_result, sae_delay_result, wl_slew_result, sae_slew_result, bl_delay_result, bl_slew_result, power_result) def get_model_delays(self, port): """Get model delays based on port. Currently assumes single RW port.""" return self.sram.control_logic_rw.get_wl_sen_delays() def get_num_delay_stages(self): """Gets the number of stages in the delay chain from the control logic""" return len(self.sram.control_logic_rw.replica_bitline.delay_fanout_list) def get_num_delay_fanout_list(self): """Gets the number of stages in the delay chain from the control logic""" return self.sram.control_logic_rw.replica_bitline.delay_fanout_list def get_num_delay_stage_fanout(self): """Gets fanout in each stage in the delay chain. Assumes each stage is the same""" return self.sram.control_logic_rw.replica_bitline.delay_fanout_list[0] def get_num_wl_en_driver_stages(self): """Gets the number of stages in the wl_en driver from the control logic""" return self.sram.control_logic_rw.wl_en_driver.num_stages def get_num_sen_driver_stages(self): """Gets the number of stages in the sen driver from the control logic""" return self.sram.control_logic_rw.s_en_driver.num_stages def get_num_wl_driver_stages(self): """Gets the number of stages in the wordline driver from the control logic""" return self.sram.bank.wordline_driver.inv.num_stages def scale_delays(self, delay_list): """Takes in a list of measured delays and convert it to simple units to easily compare to model values.""" converted_values = [] #Calculate average total = 0 for meas_value in delay_list: total+=meas_value average = total/len(delay_list)
def min_max_normalization(self, value_list): """Re-scales input values on a range from 0-1 where min(list)=0, max(list)=1""" scaled_values = [] min_max_diff = max(value_list) - min(value_list) average = sum(value_list)/len(value_list) for value in value_list: scaled_values.append((value-average)/(min_max_diff)) return scaled_values def calculate_error_l2_norm(self, list_a, list_b): """Calculates error between two lists using the l2 norm""" error_list = [] for val_a, val_b in zip(list_a, list_b): error_list.append((val_a-val_b)**2) return error_list def compare_measured_and_model(self, measured_vals, model_vals): """First scales both inputs into similar ranges and then compares the error between both.""" scaled_meas = self.min_max_normalization(measured_vals) debug.info(1, "Scaled measurements:\n{}".format(scaled_meas)) scaled_model = self.min_max_normalization(model_vals) debug.info(1, "Scaled model:\n{}".format(scaled_model)) errors = self.calculate_error_l2_norm(scaled_meas, scaled_model) debug.info(1, "Errors:\n{}\n".format(errors)) def analyze(self, probe_address, probe_data, slews, loads, port): """Measures entire delay path along the wordline and sense amp enable and compare it to the model delays.""" self.load=max(loads) self.slew=max(slews) self.set_probe(probe_address, probe_data) self.create_signal_names(port) self.create_measurement_names(port) self.create_measurement_objects() data_dict = {} read_port = self.read_ports[0] #only test the first read port read_port = port self.targ_read_ports = [read_port] self.targ_write_ports = [self.write_ports[0]] debug.info(1,"Model test: corner {}".format(self.corner)) (success, wl_delays, sae_delays, wl_slews, sae_slews, bl_delays, bl_slews, powers)=self.run_delay_simulation() debug.check(success, "Model measurements Failed: period={}".format(self.period)) debug.info(1,"Measured Wordline delays (ns):\n\t {}".format(wl_delays[read_port])) debug.info(1,"Measured Wordline slews:\n\t {}".format(wl_slews[read_port])) debug.info(1,"Measured SAE delays (ns):\n\t {}".format(sae_delays[read_port])) debug.info(1,"Measured SAE slews:\n\t {}".format(sae_slews[read_port])) debug.info(1,"Measured Bitline delays (ns):\n\t {}".format(bl_delays[read_port])) data_dict[self.wl_meas_name] = wl_delays[read_port] data_dict[self.sae_meas_name] = sae_delays[read_port] data_dict[self.wl_slew_name] = wl_slews[read_port] data_dict[self.sae_slew_name] = sae_slews[read_port] data_dict[self.bl_meas_name] = bl_delays[read_port] data_dict[self.power_name] = powers[read_port] if OPTS.auto_delay_chain_sizing: #Model is not used in this case wl_model_delays, sae_model_delays = self.get_model_delays(read_port) debug.info(1,"Wordline model delays:\n\t {}".format(wl_model_delays)) debug.info(1,"SAE model delays:\n\t {}".format(sae_model_delays)) data_dict[self.wl_model_name] = wl_model_delays data_dict[self.sae_model_name] = sae_model_delays #Some evaluations of the model and measured values # debug.info(1, "Comparing wordline measurements and model.") # self.compare_measured_and_model(wl_delays[read_port], wl_model_delays) # debug.info(1, "Comparing SAE measurements and model") # self.compare_measured_and_model(sae_delays[read_port], sae_model_delays) return data_dict def get_all_signal_names(self): """Returns all signals names as a dict indexed by hardcoded names. Useful for writing the head of the CSV.""" name_dict = {} #Signal names are more descriptive than the measurement names, first value trimmed to match size of measurements names. name_dict[self.wl_meas_name] = self.wl_signal_names[1:] name_dict[self.sae_meas_name] = self.rbl_en_signal_names[1:]+self.sae_signal_names[1:] name_dict[self.wl_slew_name] = self.wl_slew_meas_names name_dict[self.sae_slew_name] = self.rbl_slew_meas_names+self.sae_slew_meas_names name_dict[self.bl_meas_name] = self.bitline_meas_names[0:1] name_dict[self.power_name] = self.power_meas_names #name_dict[self.wl_slew_name] = self.wl_slew_meas_names if OPTS.auto_delay_chain_sizing: name_dict[self.wl_model_name] = name_dict["wl_measures"] #model uses same names as measured. name_dict[self.sae_model_name] = name_dict["sae_measures"] return name_dict
#Convert values for meas_value in delay_list: converted_values.append(meas_value/average) return converted_values
pc_get_cluster.go
package main import ( "crypto/tls" "encoding/json" "fmt" "net/http" nutanix "github.com/routebyintuition/ntnx-go-sdk" "github.com/routebyintuition/ntnx-go-sdk/pc" ) func main() { fmt.Println("testing prism central get one cluster...") httpClient := &http.Client{Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }} // pccon := &pc.ServiceConfig{URL: nutanix.String("https://10.1.1.10:9440/api/nutanix/v3/")} // con, err := nutanix.NewClient(httpClient, &nutanix.Config{PrismCentral: pccon}) con, err := nutanix.NewClient(httpClient, &nutanix.Config{PrismCentral: new(pc.ServiceConfig)}) if err != nil { fmt.Println("error on NewClient: ", err)
cGetRequest := new(pc.ClusterGetRequest) cGetRequest.UUID = "0005ad73-a7b6-cb49-2e13-ac1f6b35bfb8" getRes, _, err := con.PC.Cluster.Get(cGetRequest) if err != nil { fmt.Println("cluster list error: ", err) return } // fmt.Println("cluster list response: ", listResp) out, _ := json.MarshalIndent(getRes, "", " ") fmt.Println("cluster list result: ", string(out)) }
}
image_loader.rs
use rltk::rex::XpFile; use super::{Map, TileType}; /// Loads a RexPaint file, and converts it into our map format pub fn
(new_depth: i32, xp_file : &XpFile) -> Map { let mut map : Map = Map::new(new_depth); for layer in &xp_file.layers { for y in 0..layer.height { for x in 0..layer.width { let cell = layer.get(x, y).unwrap(); if x < map.width as usize && y < map.height as usize { let idx = map.xy_idx(x as i32, y as i32); match cell.ch { 32 => map.tiles[idx] = TileType::Floor, // # 35 => map.tiles[idx] = TileType::Wall, // # _ => {} } } } } } map }
load_rex_map
handler.iqRecommend.go
package main import ( "io/ioutil" "github.com/nlopes/slack" "net/http" "log" "bytes" "strings" ) // Sample from https://github.com/nlopes/slack/blob/master/examples/slash/slash.go // TODO: look at https://glitch.com/edit/#!/slack-slash-command-and-dialogs-blueprint?path=src/index.js:1:0 for posting a dialog box to type in the maven gav func iqRecommend(w http.ResponseWriter, r *http.Request) { switch method := r.Method; method { case http.MethodPost: s, err := slack.SlashCommandParse(r) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("[ERROR] %s\n", err) return } if !s.ValidateToken(config.VerificationToken) { w.WriteHeader(http.StatusUnauthorized) return } switch s.Command { case "/iq-recommend": w.WriteHeader(http.StatusOK) mavenCoordinate, err := ParseMavenCoordinate(s.Text) if (err != nil) { log.Printf("[DEBUG] %s\n", err) w.Header().Set("Content-Type", "application/json") w.Write([]byte("I didn't get that.\n")) w.Write([]byte(err.Error() + "\n")) w.Write([]byte("Why don't you just tell me what you're looking for.\n")) w.Write([]byte("HINT: I only understand \"groupId:artifactId:version\"\n")) } else { rr := lookupRecommendation(mavenCoordinate) if (len(rr.Remediation.VersionChanges) == 0) { w.Header().Set("Content-Type", "application/json") w.Write([]byte("No recommendation found for: " + s.Text)) } else { w.Header().Set("Content-Type", "application/json") w.Write([]byte("Looking up a recommendation for:" + s.Text + ". Sometimes I have to look really hard. Watch for a DM from me in a bit.")) //SlashCommand Struct = https://github.com/nlopes/slack/blob/master/slash.go sendMessage(s.Text, s.ChannelID, s.UserID, rr.Remediation.VersionChanges[0].Type, rr.Remediation.VersionChanges[0].Data.Component.ComponentIdentifier.Coordinates.Version, lookupAllVersions(mavenCoordinate)) } } default: w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Unsupported slash command.")) } default: w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Unsupported request method.")) } } //https://github.com/nlopes/slack/blob/master/chat.go -> https://api.slack.com/docs/formatting -> http://davestevens.github.io/slack-message-builder/ func sendMessage(pText string, pChannelID string, pUserID string, pRemediationType string, pRecommendedVersion string, pAllVersions []string)
func lookupRecommendation(pGAV MavenCoordinate) RemediationResponse { httpClient := http.Client{} //url := "http://localhost:8060/iq/api/v2/organizations" url := "http://localhost:60359/iq/api/v2/components/remediation/application/e06a119c75d04d97b8d8c11b62719752" //url := "http://localhost:8060/iq/api/v2/components/remediation/application/e06a119c75d04d97b8d8c11b62719752" book := CI{ComponentIdentifier: ComponentIdentifier{ Format: "maven", Coordinates: MavenCoordinate{ GroupID: pGAV.GroupID, //"org.apache.logging.log4j", ArtifactID: pGAV.ArtifactID, //log4j-core Classifier: pGAV.Classifier, //"", Extension : pGAV.Extension, //"jar", Version: pGAV.Version, //"2.8", }, }, } r, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(book.ToComponentIdentifierJSON())) r.SetBasicAuth("admin", "admin123") r.Header.Add("Content-Type", "application/json") orgs, err := httpClient.Do(r) if err != nil { log.Fatal(err) } body, err := ioutil.ReadAll(orgs.Body) if err != nil { log.Println("[ERROR] could not read body") } remediationResponse := FromRemediationResponseJSON(body) //log.Printf("[DEBUG] Orgs: %s\n", body) //log.Printf("[DEBUG] RR: %s\n", remediationResponse) return remediationResponse } func lookupAllVersions(pGAV MavenCoordinate) []string { httpClient := http.Client{} url := "http://localhost:60359/iq/api/v2/components/versions" //url := "http://localhost:8060/iq/api/v2/components/versions" book := ComponentIdentifier{ Format: "maven", Coordinates: MavenCoordinate{ GroupID: pGAV.GroupID, //"org.apache.logging.log4j", ArtifactID: pGAV.ArtifactID, //log4j-core Classifier: pGAV.Classifier, //"", Extension : pGAV.Extension, //"jar", Version: pGAV.Version, //"2.8", }, } r, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(book.ToComponentIdentifierJSON())) r.SetBasicAuth("admin", "admin123") r.Header.Add("Content-Type", "application/json") orgs, err := httpClient.Do(r) if err != nil { log.Fatal(err) } body, err := ioutil.ReadAll(orgs.Body) if err != nil { log.Println("[ERROR] could not read body") } allVersions := FromAllVersionsJSON(body) // log.Printf("[DEBUG] Orgs: %s\n", body) // log.Printf("[DEBUG] RR: %s\n", allVersions) return allVersions }
{ slackAPI := slack.New(config.BotToken) _, _, dmChannelID, err := slackAPI.OpenIMChannel(pUserID) if err != nil { log.Printf("[ERROR] %s\n", err) return } attachment := slack.Attachment{ Text: pRecommendedVersion, Title: pRemediationType + " Recommended Version:", } allVersAttachment := slack.Attachment{ Text: strings.Join(pAllVersions, " | "), Title: "All Versions", } //todo: send to the bot channelID, timestamp, err := slackAPI.PostMessage(dmChannelID, slack.MsgOptionText("Looking up a recommendation for: " + pText, false), slack.MsgOptionAttachments(allVersAttachment, attachment)) if err != nil { log.Printf("[ERROR] %s\n", err) return } log.Printf("Message successfully sent to channel %s at %s", channelID, timestamp) }
machinelearningcompute.go
package machinelearningservices // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // MachineLearningComputeClient is the these APIs allow end users to operate on Azure Machine Learning Workspace // resources. type MachineLearningComputeClient struct { BaseClient } // NewMachineLearningComputeClient creates an instance of the MachineLearningComputeClient client. func NewMachineLearningComputeClient(subscriptionID string) MachineLearningComputeClient { return NewMachineLearningComputeClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewMachineLearningComputeClientWithBaseURI creates an instance of the MachineLearningComputeClient client using a // custom endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, // Azure stack). func NewMachineLearningComputeClientWithBaseURI(baseURI string, subscriptionID string) MachineLearningComputeClient { return MachineLearningComputeClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates or updates compute. This call will overwrite a compute if it exists. This is a nonrecoverable // operation. If your intent is to create a new compute, do a GET first to verify that it does not exist yet. // Parameters: // resourceGroupName - name of the resource group in which workspace is located. // workspaceName - name of Azure Machine Learning workspace. // computeName - name of the Azure Machine Learning compute. // parameters - payload with Machine Learning compute definition. func (client MachineLearningComputeClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, workspaceName string, computeName string, parameters ComputeResource) (result MachineLearningComputeCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/MachineLearningComputeClient.CreateOrUpdate") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, workspaceName, computeName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client MachineLearningComputeClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, workspaceName string, computeName string, parameters ComputeResource) (*http.Request, error) { pathParameters := map[string]interface{}{ "computeName": autorest.Encode("path", computeName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "workspaceName": autorest.Encode("path", workspaceName), } const APIVersion = "2019-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client MachineLearningComputeClient) CreateOrUpdateSender(req *http.Request) (future MachineLearningComputeCreateOrUpdateFuture, err error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client MachineLearningComputeClient) CreateOrUpdateResponder(resp *http.Response) (result ComputeResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes specified Machine Learning compute. // Parameters: // resourceGroupName - name of the resource group in which workspace is located. // workspaceName - name of Azure Machine Learning workspace. // computeName - name of the Azure Machine Learning compute. // underlyingResourceAction - delete the underlying compute if 'Delete', or detach the underlying compute from // workspace if 'Detach'. func (client MachineLearningComputeClient) Delete(ctx context.Context, resourceGroupName string, workspaceName string, computeName string, underlyingResourceAction UnderlyingResourceAction) (result MachineLearningComputeDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/MachineLearningComputeClient.Delete") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeletePreparer(ctx, resourceGroupName, workspaceName, computeName, underlyingResourceAction) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client MachineLearningComputeClient) DeletePreparer(ctx context.Context, resourceGroupName string, workspaceName string, computeName string, underlyingResourceAction UnderlyingResourceAction) (*http.Request, error) { pathParameters := map[string]interface{}{ "computeName": autorest.Encode("path", computeName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "workspaceName": autorest.Encode("path", workspaceName), } const APIVersion = "2019-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, "underlyingResourceAction": autorest.Encode("query", underlyingResourceAction), } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client MachineLearningComputeClient) DeleteSender(req *http.Request) (future MachineLearningComputeDeleteFuture, err error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client MachineLearningComputeClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByClosing()) result.Response = resp return } // Get gets compute definition by its name. Any secrets (storage keys, service credentials, etc) are not returned - use // 'keys' nested resource to get them. // Parameters: // resourceGroupName - name of the resource group in which workspace is located. // workspaceName - name of Azure Machine Learning workspace. // computeName - name of the Azure Machine Learning compute. func (client MachineLearningComputeClient) Get(ctx context.Context, resourceGroupName string, workspaceName string, computeName string) (result ComputeResource, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/MachineLearningComputeClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, workspaceName, computeName) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client MachineLearningComputeClient) GetPreparer(ctx context.Context, resourceGroupName string, workspaceName string, computeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "computeName": autorest.Encode("path", computeName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "workspaceName": autorest.Encode("path", workspaceName), } const APIVersion = "2019-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client MachineLearningComputeClient) GetSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body.
func (client MachineLearningComputeClient) GetResponder(resp *http.Response) (result ComputeResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListByWorkspace gets computes in specified workspace. // Parameters: // resourceGroupName - name of the resource group in which workspace is located. // workspaceName - name of Azure Machine Learning workspace. // skiptoken - continuation token for pagination. func (client MachineLearningComputeClient) ListByWorkspace(ctx context.Context, resourceGroupName string, workspaceName string, skiptoken string) (result PaginatedComputeResourcesListPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/MachineLearningComputeClient.ListByWorkspace") defer func() { sc := -1 if result.pcrl.Response.Response != nil { sc = result.pcrl.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listByWorkspaceNextResults req, err := client.ListByWorkspacePreparer(ctx, resourceGroupName, workspaceName, skiptoken) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "ListByWorkspace", nil, "Failure preparing request") return } resp, err := client.ListByWorkspaceSender(req) if err != nil { result.pcrl.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "ListByWorkspace", resp, "Failure sending request") return } result.pcrl, err = client.ListByWorkspaceResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "ListByWorkspace", resp, "Failure responding to request") } return } // ListByWorkspacePreparer prepares the ListByWorkspace request. func (client MachineLearningComputeClient) ListByWorkspacePreparer(ctx context.Context, resourceGroupName string, workspaceName string, skiptoken string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "workspaceName": autorest.Encode("path", workspaceName), } const APIVersion = "2019-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(skiptoken) > 0 { queryParameters["$skiptoken"] = autorest.Encode("query", skiptoken) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByWorkspaceSender sends the ListByWorkspace request. The method will close the // http.Response Body if it receives an error. func (client MachineLearningComputeClient) ListByWorkspaceSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListByWorkspaceResponder handles the response to the ListByWorkspace request. The method always // closes the http.Response Body. func (client MachineLearningComputeClient) ListByWorkspaceResponder(resp *http.Response) (result PaginatedComputeResourcesList, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByWorkspaceNextResults retrieves the next set of results, if any. func (client MachineLearningComputeClient) listByWorkspaceNextResults(ctx context.Context, lastResults PaginatedComputeResourcesList) (result PaginatedComputeResourcesList, err error) { req, err := lastResults.paginatedComputeResourcesListPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "listByWorkspaceNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByWorkspaceSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "listByWorkspaceNextResults", resp, "Failure sending next results request") } result, err = client.ListByWorkspaceResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "listByWorkspaceNextResults", resp, "Failure responding to next results request") } return } // ListByWorkspaceComplete enumerates all values, automatically crossing page boundaries as required. func (client MachineLearningComputeClient) ListByWorkspaceComplete(ctx context.Context, resourceGroupName string, workspaceName string, skiptoken string) (result PaginatedComputeResourcesListIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/MachineLearningComputeClient.ListByWorkspace") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListByWorkspace(ctx, resourceGroupName, workspaceName, skiptoken) return } // ListKeys gets secrets related to Machine Learning compute (storage keys, service credentials, etc). // Parameters: // resourceGroupName - name of the resource group in which workspace is located. // workspaceName - name of Azure Machine Learning workspace. // computeName - name of the Azure Machine Learning compute. func (client MachineLearningComputeClient) ListKeys(ctx context.Context, resourceGroupName string, workspaceName string, computeName string) (result ComputeSecretsModel, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/MachineLearningComputeClient.ListKeys") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ListKeysPreparer(ctx, resourceGroupName, workspaceName, computeName) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "ListKeys", nil, "Failure preparing request") return } resp, err := client.ListKeysSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "ListKeys", resp, "Failure sending request") return } result, err = client.ListKeysResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "ListKeys", resp, "Failure responding to request") } return } // ListKeysPreparer prepares the ListKeys request. func (client MachineLearningComputeClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, workspaceName string, computeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "computeName": autorest.Encode("path", computeName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "workspaceName": autorest.Encode("path", workspaceName), } const APIVersion = "2019-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}/listKeys", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListKeysSender sends the ListKeys request. The method will close the // http.Response Body if it receives an error. func (client MachineLearningComputeClient) ListKeysSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListKeysResponder handles the response to the ListKeys request. The method always // closes the http.Response Body. func (client MachineLearningComputeClient) ListKeysResponder(resp *http.Response) (result ComputeSecretsModel, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListNodes get the details (e.g IP address, port etc) of all the compute nodes in the compute. // Parameters: // resourceGroupName - name of the resource group in which workspace is located. // workspaceName - name of Azure Machine Learning workspace. // computeName - name of the Azure Machine Learning compute. func (client MachineLearningComputeClient) ListNodes(ctx context.Context, resourceGroupName string, workspaceName string, computeName string) (result AmlComputeNodesInformation, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/MachineLearningComputeClient.ListNodes") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.ListNodesPreparer(ctx, resourceGroupName, workspaceName, computeName) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "ListNodes", nil, "Failure preparing request") return } resp, err := client.ListNodesSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "ListNodes", resp, "Failure sending request") return } result, err = client.ListNodesResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "ListNodes", resp, "Failure responding to request") } return } // ListNodesPreparer prepares the ListNodes request. func (client MachineLearningComputeClient) ListNodesPreparer(ctx context.Context, resourceGroupName string, workspaceName string, computeName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "computeName": autorest.Encode("path", computeName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "workspaceName": autorest.Encode("path", workspaceName), } const APIVersion = "2019-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsPost(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}/listNodes", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListNodesSender sends the ListNodes request. The method will close the // http.Response Body if it receives an error. func (client MachineLearningComputeClient) ListNodesSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListNodesResponder handles the response to the ListNodes request. The method always // closes the http.Response Body. func (client MachineLearningComputeClient) ListNodesResponder(resp *http.Response) (result AmlComputeNodesInformation, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Update updates properties of a compute. This call will overwrite a compute if it exists. This is a nonrecoverable // operation. // Parameters: // resourceGroupName - name of the resource group in which workspace is located. // workspaceName - name of Azure Machine Learning workspace. // computeName - name of the Azure Machine Learning compute. // parameters - additional parameters for cluster update. func (client MachineLearningComputeClient) Update(ctx context.Context, resourceGroupName string, workspaceName string, computeName string, parameters ClusterUpdateParameters) (result MachineLearningComputeUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/MachineLearningComputeClient.Update") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.UpdatePreparer(ctx, resourceGroupName, workspaceName, computeName, parameters) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "Update", nil, "Failure preparing request") return } result, err = client.UpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "machinelearningservices.MachineLearningComputeClient", "Update", result.Response(), "Failure sending request") return } return } // UpdatePreparer prepares the Update request. func (client MachineLearningComputeClient) UpdatePreparer(ctx context.Context, resourceGroupName string, workspaceName string, computeName string, parameters ClusterUpdateParameters) (*http.Request, error) { pathParameters := map[string]interface{}{ "computeName": autorest.Encode("path", computeName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "workspaceName": autorest.Encode("path", workspaceName), } const APIVersion = "2019-05-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}/computes/{computeName}", pathParameters), autorest.WithJSON(parameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateSender sends the Update request. The method will close the // http.Response Body if it receives an error. func (client MachineLearningComputeClient) UpdateSender(req *http.Request) (future MachineLearningComputeUpdateFuture, err error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) var resp *http.Response resp, err = autorest.SendWithSender(client, req, sd...) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // UpdateResponder handles the response to the Update request. The method always // closes the http.Response Body. func (client MachineLearningComputeClient) UpdateResponder(resp *http.Response) (result ComputeResource, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
plot.go
package output import ( "fmt" "io" "time" "github.com/nicholasjackson/bench/results" "github.com/wcharczuk/go-chart" "github.com/wcharczuk/go-chart/drawing" ) // PlotData plots the results onto a graph and saves the output to the given writer func PlotData(interval time.Duration, r results.ResultSet, w io.Writer) { set := r.Reduce(interval) t := results.TabularResults{} rows := t.Tabulate(set) seriesY := createYSeries(rows) seriesX := createXSeries(rows) ticks := createXTicks(rows) graph := chart.Chart{ Background: chart.Style{ Padding: chart.Box{ Top: 50, Left: 25, Right: 25, Bottom: 25, }, FillColor: drawing.ColorFromHex("efefef"), }, XAxis: chart.XAxis{ Name: "Elapsed Time (s)", NameStyle: chart.StyleShow(), Style: chart.StyleShow(), ValueFormatter: func(v interface{}) string { return fmt.Sprintf("%.0f", v) }, Ticks: ticks, }, YAxis: chart.YAxis{ Name: "Count", NameStyle: chart.StyleShow(), Style: chart.StyleShow(), ValueFormatter: func(v interface{}) string { return fmt.Sprintf("%.0f", v) }, }, YAxisSecondary: chart.YAxis{ Name: "Time (ms)", NameStyle: chart.StyleShow(), Style: chart.StyleShow(), ValueFormatter: func(v interface{}) string { return fmt.Sprintf("%.2f", v) }, }, Series: []chart.Series{ chart.ContinuousSeries{ Name: "Success", XValues: seriesX["x"], YValues: seriesY["y.success"], Style: chart.Style{ Show: true, //note; if we set ANY other properties, we must set this to true. StrokeColor: drawing.ColorGreen, // will supercede defaults FillColor: drawing.ColorGreen.WithAlpha(64), // will supercede defaults }, }, chart.ContinuousSeries{ Name: "Failure", XValues: seriesX["x"], YValues: seriesY["y.failure"], Style: chart.Style{ Show: true, //note; if we set ANY other properties, we must set this to true. StrokeColor: drawing.ColorRed, // will supercede defaults FillColor: drawing.ColorRed.WithAlpha(64), // will supercede defaults }, }, chart.ContinuousSeries{ Name: "Timeout",
Style: chart.Style{ Show: true, //note; if we set ANY other properties, we must set this to true. StrokeColor: drawing.ColorFromHex("FFD133"), // will supercede defaults FillColor: drawing.ColorFromHex("FFD133").WithAlpha(64), // will supercede defaults }, }, chart.ContinuousSeries{ Name: "Threads", XValues: seriesX["x"], YValues: seriesY["y.threads"], Style: chart.Style{ Show: true, //note; if we set ANY other properties, we must set this to true. StrokeColor: drawing.ColorFromHex("FF338D"), // will supercede defaults }, }, chart.ContinuousSeries{ YAxis: chart.YAxisSecondary, Name: "Request time (ms)", XValues: seriesX["x"], YValues: seriesY["y.request"], Style: chart.Style{ Show: true, //note; if we set ANY other properties, we must set this to true. StrokeColor: drawing.ColorBlue, // will supercede defaults }, }, }, } //note we have to do this as a separate step because we need a reference to graph graph.Elements = []chart.Renderable{ chart.Legend(&graph), } graph.Render(chart.PNG, w) } func createXTicks(results []results.Row) []chart.Tick { var ticks []chart.Tick maxTicks := 20 totalTime := results[len(results)-1].ElapsedTime.Seconds() tickInterval := float64(totalTime) / float64(maxTicks) fmt.Println(tickInterval) nextTick := 0.0 for i := range results { if tickInterval < 1 || float64(i) >= nextTick { tick := chart.Tick{ Value: nextTick, Label: fmt.Sprintf("%.0f", nextTick), } ticks = append(ticks, tick) nextTick += tickInterval } } // add one last tick for the end lastTick := results[len(results)-1].ElapsedTime tick := chart.Tick{ Value: lastTick.Seconds(), Label: fmt.Sprintf("%.0f", lastTick.Seconds()), } ticks = append(ticks, tick) return ticks } func createXSeries(results []results.Row) map[string][]float64 { series := map[string][]float64{ "x": make([]float64, 0), } for _, row := range results { series["x"] = append(series["x"], row.ElapsedTime.Seconds()) } return series } func createYSeries(results []results.Row) map[string][]float64 { series := map[string][]float64{ "y.success": make([]float64, 0), "y.failure": make([]float64, 0), "y.timeout": make([]float64, 0), "y.request": make([]float64, 0), "y.threads": make([]float64, 0), } for _, row := range results { series["y.success"] = append(series["y.success"], float64(row.TotalSuccess)) series["y.failure"] = append(series["y.failure"], float64(row.TotalFailures)) series["y.timeout"] = append(series["y.timeout"], float64(row.TotalTimeouts)) series["y.threads"] = append(series["y.threads"], float64(row.Threads)) series["y.request"] = append(series["y.request"], float64(row.AvgRequestTime.Nanoseconds()/1e6)) } return series }
XValues: seriesX["x"], YValues: seriesY["y.timeout"],
taoyizhu.py
import execjs def get_js_function(js_path, func_name, *func_args):
nt(passwd) print('*'*80) print('@欢迎Star!') print('@有问题请联系: [email protected]')
''' 获取指定目录下的js代码, 并且指定js代码中函数的名字以及函数的参数。 :param js_path: js代码的位置 :param func_name: js代码中函数的名字 :param func_args: js代码中函数的参数 :return: 返回调用js函数的结果 ''' with open(js_path, encoding='utf-8') as fp: js = fp.read() ctx = execjs.compile(js) return ctx.call(func_name, func_args[0], func_args[1]) if __name__ == '__main__': # 给个star吧 passwd = get_js_function('xiami.js', '_s', "") print('*'*80) pri
proxy_client.py
#!/usr/bin/env python3 import socket # CONSTANTS OUTBOUND_HOST = "127.0.0.1" OUTBOUND_PORT = 8001 OUTBOUND_BUFFER_SIZE = 1024 PAYLOAD_URL = "www.google.com" PAYLOAD = f"GET / HTTP/1.0\r\nHost: {PAYLOAD_URL}\r\n\r\n" def main(): # Create a socket object
if __name__ == "__main__": main()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # Connect to the proxy server s.connect((OUTBOUND_HOST, OUTBOUND_PORT)) # Send the payload to the proxy server s.sendall(PAYLOAD.encode()) # Get IP and port of peer peer_addr = s.getpeername() # No longer write/send s.shutdown(socket.SHUT_WR) # Reading data until no more left data = b"" while True: fetched_data = s.recv(OUTBOUND_BUFFER_SIZE) if not fetched_data: break data += fetched_data print("Received From:", str(peer_addr[0]) + ":" + str(peer_addr[1]), "Content:", data)
client.ts
import { OutputClient } from '../../types'; import { GeneratorClientExtra, GeneratorOperations, GeneratorOptions, GeneratorVerbsOptions, } from '../../types/generator'; import { pascal } from '../../utils/case'; import { generateAngular, generateAngularFooter, generateAngularHeader, generateAngularTitle, getAngularDependencies, } from './angular'; import { generateAxios, generateAxiosFooter, generateAxiosHeader, generateAxiosTitle, getAxiosDependencies, } from './axios'; import { generateDependencyImports } from './imports'; import { generateMSW } from './msw'; import { generateReactQuery, generateReactQueryFooter, generateReactQueryHeader, generateReactQueryTitle, getReactQueryDependencies, } from './react-query'; const DEFAULT_CLIENT = OutputClient.AXIOS;
const GENERATOR_CLIENT = { [OutputClient.AXIOS]: { client: generateAxios, msw: generateMSW, header: generateAxiosHeader, dependencies: getAxiosDependencies, footer: generateAxiosFooter, title: generateAxiosTitle, }, [OutputClient.ANGULAR]: { client: generateAngular, msw: generateMSW, header: generateAngularHeader, dependencies: getAngularDependencies, footer: generateAngularFooter, title: generateAngularTitle, }, [OutputClient.REACT_QUERY]: { client: generateReactQuery, msw: generateMSW, header: generateReactQueryHeader, dependencies: getReactQueryDependencies, footer: generateReactQueryFooter, title: generateReactQueryTitle, }, }; export const generateClientImports = ( client = DEFAULT_CLIENT, implementation: string, imports: { exports: string[]; dependency: string; }[], ): string => generateDependencyImports(implementation, [ ...GENERATOR_CLIENT[client].dependencies(), ...imports, ]); export const generateClientHeader = ( outputClient: OutputClient = DEFAULT_CLIENT, title: string, customTitleFunc?: (title: string) => string, ): GeneratorClientExtra => { const titles = generateClientTitle(outputClient, title, customTitleFunc); return { implementation: GENERATOR_CLIENT[outputClient].header( titles.implementation, ), implementationMSW: `export const ${titles.implementationMSW} = () => [\n`, }; }; export const generateClientFooter = ( outputClient: OutputClient = DEFAULT_CLIENT, ): GeneratorClientExtra => { return { implementation: GENERATOR_CLIENT[outputClient].footer(), implementationMSW: `]\n`, }; }; export const generateClientTitle = ( outputClient: OutputClient = DEFAULT_CLIENT, title: string, customTitleFunc?: (title: string) => string, ) => { if (customTitleFunc) { const customTitle = customTitleFunc(title); return { implementation: GENERATOR_CLIENT[outputClient].title(customTitle), implementationMSW: `get${pascal(customTitle)}MSW`, }; } return { implementation: GENERATOR_CLIENT[outputClient].title(title), implementationMSW: `get${pascal(title)}MSW`, }; }; export const generateClient = ( outputClient: OutputClient = DEFAULT_CLIENT, verbsOptions: GeneratorVerbsOptions, options: GeneratorOptions, ): GeneratorOperations => { return verbsOptions.reduce((acc, verbOption) => { const generator = GENERATOR_CLIENT[outputClient]; const client = generator.client(verbOption, options); const msw = options.mock ? generator.msw(verbOption, options) : { implementation: '', imports: [], }; return { ...acc, [verbOption.operationId]: { implementation: client.implementation, imports: client.imports, implementationMSW: msw.implementation, importsMSW: msw.imports, tags: verbOption.tags, mutator: verbOption.mutator, }, }; }, {}); };
loader.py
#!/usr/bin/env python # encoding: utf-8 """ """ from web import Storage from teslafaas.container.webpy.context_manager import ContextManager from teslafaas.container.webpy.http_error_process import customize_http_error import os import sys import web import json import pkgutil import logging import importlib from codecs import open from teslafaas.container.webpy.init import init_all from teslafaas.container.webpy.common import urls as global_urls __author__ = 'adonis' init_all(use_gevent=False) class InvalidUserApp(Exception): pass class DummyModule(dict): def __init__(self, **kw): super(DummyModule, self).__init__(**kw) def __getattr__(self, key): # FIXME: vars() support, vars() will not come here # if key == '__dict__': # return {k: v for k, v in self.iteritems()} try: return self[key] except KeyError: raise AttributeError( r"'DummyModule' object has no attribute '%s'" % key) def __setattr__(self, key, value): self[key] = value # FIXME: vars() support self.__dict__[key] = value def webpy_wsgifunc_wrapper(self): conf = self.conf webpy_app = self.webpy_app # TODO: load dynamic resource manager = ContextManager(webpy_app, conf, raw_mod=self.raw_mod) manager.load_middle_ware() manager.set_context_hook() return webpy_app.wsgifunc() class ContainerLoader(object): def __init__(self, init_context): self.conf = {} self.init_context = init_context def
(self, mod, conf, urls): wsgi_mod = DummyModule() app = web.application(urls, globals(), autoreload=False) customize_http_error(app) # Unable to set a FunctionType to instance and void conflict # app.wsgi = FunctionType app.wsgifunc() # TODO: wrap wsgifunc to do dynamic resource reload, refresh automatically wsgi_mod.conf = conf wsgi_mod.raw_mod = mod wsgi_mod.webpy_app = app manager = ContextManager(app, conf, raw_mod=mod) manager.load_middle_ware() manager.set_context_hook() wsgi_mod.wsgifunc = app.wsgifunc() # wsgi_mod.refresh = return wsgi_mod def _import_sub_modules(self, mod): for importer, modname, ispkg in pkgutil.walk_packages(path=mod.__path__, prefix=mod.__name__+'.'): __import__(modname) def load_module(self, src_path, container_name=None, env="common"): """ :param src_path: user module dir path :param container_name: used for url router and unix socket name, default: last dir name of src_path :return: 2-item tuple, wsgi module name and container name Gunicorn used python app module name, with wsgifunc() entry function """ base_dir = os.path.abspath(src_path.rstrip('/')) module_name = dir_name = os.path.basename(base_dir) src_parent_path = os.path.dirname(base_dir) if not container_name: container_name = dir_name if src_parent_path not in sys.path: sys.path.append(src_parent_path) # TODO: add src to python path if src_parent_path not in sys.path: sys.path.append(src_parent_path) # if module_name in sys.modules: # raise InvalidUserApp( # "Invalid module name '%s': conflict with a already exist " # "module(%s), please change a name" # % (module_name, sys.modules[module_name].__file__)) try: raw_module = __import__(module_name) except ImportError: raise InvalidUserApp( "Can't import '%s' after add '%s' to PYTHONPATH. " "Please check if __init__.py exist in '%s'" % (dir_name, src_parent_path, src_path)) # conf_suffix = "" # if env != "common": # if env == "DAILY": # conf_suffix = "_daily" # elif env == "PRE": # conf_suffix = "_pre" # elif env == "PRODUCTION": # conf_suffix = "_prod" # if os.path.exists(os.path.join(x, 'conf%s.ini' % conf_suffix)): # config.update(self.parse_ini_conf(os.path.join(x, 'conf%s.ini' % conf_suffix))) # shutil.copyfile(os.path.join(x, 'conf%s.ini' % conf_suffix), os.path.join(x, 'conf.ini')) # if os.path.exists(os.path.join(x, 'conf%s.json' % conf_suffix)): # config.update(self.parse_json_conf(os.path.join(x, 'conf%s.json' % conf_suffix))) # shutil.copyfile(os.path.join(x, 'conf%s.json' % conf_suffix), os.path.join(x, 'conf.json')) # if os.path.exists(os.path.join(x, 'conf%s.py' % conf_suffix)): # config.update(self.parse_py_conf("%s.%s" % (mod_name, 'conf%s' % conf_suffix))) # shutil.copyfile(os.path.join(x, 'conf%s.py' % conf_suffix), os.path.join(x, 'conf.py')) # # FIXME: conflict for multiple containers # if src_path not in sys.path: # sys.path.append(src_path) urls = self.load_urls(raw_module, self.init_context.config) # 兼容老的 sub factory 用法 try: __import__('%s.factory' % raw_module.__name__) except ImportError: pass else: print 'importing module and submodules: %s.factory' % raw_module.__name__ self._import_sub_modules(getattr(raw_module, 'factory')) wsgi_module_name = "%s.%s" % ('teslafaas.container.wsgi_mods', module_name) wsgi_module = self.wrap_webpy_raw_module(raw_module, conf=self.init_context.config, urls=urls) sys.modules[wsgi_module_name] = wsgi_module return wsgi_module, container_name def load_urls(self, raw_mod, config): handlers = self.load_handlers(raw_mod, config) global global_urls if os.path.exists(os.path.join(raw_mod.__path__[0] + '/urls.py')): logging.info('importing module: %s.urls', raw_mod.__name__) __import__('%s.urls' % raw_mod.__name__) if hasattr(raw_mod.urls, 'urls'): m_urls = getattr(raw_mod.urls, 'urls') if not global_urls is m_urls: global_urls.extend(m_urls) if config.get('disable_index', False) is True: from teslafaas.container.webpy.common.IndexHandler import IndexHandler global_urls += [r"/", IndexHandler] for i in xrange(1, len(global_urls), 2): if type(global_urls[i]) == str: hname = global_urls[i] if hname not in handlers: print 'Error: cannot find handler class for %s' % hname global_urls[i] = handlers[hname] return global_urls def load_handlers(self, raw_mod, config): handlers = {} path = os.path.join(raw_mod.__path__[0] + '/handlers') if not os.path.exists(path): return handlers from teslafaas.container.webpy.common.BaseHandler import BaseHandler for f in os.listdir(path): if f.endswith('.py'): name, postfix = os.path.splitext(f) m = importlib.import_module('%s.handlers.%s' % (raw_mod.__name__, name)) for obj in dir(m): classobj = getattr(m, obj) try: if issubclass(classobj, BaseHandler): name = classobj.__name__ if name not in handlers: handlers[name] = classobj except: pass return handlers def reset_container_log(self): # """ 初始化日志配置 """ with open(os.path.join(self.root_path, 'conf/logging.json')) as f: try: log_config = json.loads(f.read()) except ValueError: raise ValueError('Invalid logging config, cannot loads to JSON') logging.dictConfig(log_config) self.logger = logging.getLogger() # set default root logger
wrap_webpy_raw_module
runtime-main.daff9c1d.js
!function(e){function t(t){for(var n,a,i=t[0],l=t[1],f=t[2],p=0,s=[];p<i.length;p++)a=i[p],Object.prototype.hasOwnProperty.call(o,a)&&o[a]&&s.push(o[a][0]),o[a]=0;for(n in l)Object.prototype.hasOwnProperty.call(l,n)&&(e[n]=l[n]);for(c&&c(t);s.length;)s.shift()();return u.push.apply(u,f||[]),r()}function r(){for(var e,t=0;t<u.length;t++){for(var r=u[t],n=!0,i=1;i<r.length;i++){var l=r[i];0!==o[l]&&(n=!1)}n&&(u.splice(t--,1),e=a(a.s=r[0]))}return e}var n={},o={1:0},u=[];function a(t){if(n[t])return n[t].exports;var r=n[t]={i:t,l:!1,exports:{}};return e[t].call(r.exports,r,r.exports,a),r.l=!0,r.exports}a.m=e,a.c=n,a.d=function(e,t,r){a.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},a.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},a.t=function(e,t){if(1&t&&(e=a(e)),8&t)return e;if(4&t&&"object"===typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(a.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)a.d(r,n,function(t){return e[t]}.bind(null,n));return r},a.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return a.d(t,"a",t),t},a.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},a.p="/";var i=this["webpackJsonpmaterial-kit-react"]=this["webpackJsonpmaterial-kit-react"]||[],l=i.push.bind(i);i.push=t,i=i.slice();for(var f=0;f<i.length;f++)t(i[f]);var c=l;r()}([]); //# sourceMappingURL=runtime-main.daff9c1d.js.map
import.go
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0. package restore import ( "bytes" "context" "crypto/tls" "strings" "sync" "sync/atomic" "time" "github.com/google/uuid" "github.com/pingcap/errors" "github.com/pingcap/failpoint" backuppb "github.com/pingcap/kvproto/pkg/brpb" "github.com/pingcap/kvproto/pkg/import_sstpb" "github.com/pingcap/kvproto/pkg/kvrpcpb" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/log" "github.com/pingcap/tidb/br/pkg/conn" berrors "github.com/pingcap/tidb/br/pkg/errors" "github.com/pingcap/tidb/br/pkg/logutil" "github.com/pingcap/tidb/br/pkg/summary" "github.com/pingcap/tidb/br/pkg/utils" pd "github.com/tikv/pd/client" "go.uber.org/multierr" "go.uber.org/zap" "golang.org/x/sync/errgroup" "google.golang.org/grpc" "google.golang.org/grpc/backoff" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/status" ) const ( importScanRegionTime = 10 * time.Second gRPCBackOffMaxDelay = 3 * time.Second ) // ImporterClient is used to import a file to TiKV. type ImporterClient interface { DownloadSST( ctx context.Context, storeID uint64, req *import_sstpb.DownloadRequest, ) (*import_sstpb.DownloadResponse, error) IngestSST( ctx context.Context, storeID uint64, req *import_sstpb.IngestRequest, ) (*import_sstpb.IngestResponse, error) MultiIngest( ctx context.Context, storeID uint64, req *import_sstpb.MultiIngestRequest, ) (*import_sstpb.IngestResponse, error) SetDownloadSpeedLimit( ctx context.Context, storeID uint64, req *import_sstpb.SetDownloadSpeedLimitRequest, ) (*import_sstpb.SetDownloadSpeedLimitResponse, error) GetImportClient( ctx context.Context, storeID uint64, ) (import_sstpb.ImportSSTClient, error) SupportMultiIngest(ctx context.Context, stores []uint64) (bool, error) } type importClient struct { mu sync.Mutex metaClient SplitClient clients map[uint64]import_sstpb.ImportSSTClient tlsConf *tls.Config keepaliveConf keepalive.ClientParameters } // NewImportClient returns a new ImporterClient. func NewImportClient(metaClient SplitClient, tlsConf *tls.Config, keepaliveConf keepalive.ClientParameters) ImporterClient { return &importClient{ metaClient: metaClient, clients: make(map[uint64]import_sstpb.ImportSSTClient), tlsConf: tlsConf, keepaliveConf: keepaliveConf, } } func (ic *importClient) DownloadSST( ctx context.Context, storeID uint64, req *import_sstpb.DownloadRequest, ) (*import_sstpb.DownloadResponse, error) { client, err := ic.GetImportClient(ctx, storeID) if err != nil { return nil, errors.Trace(err) } return client.Download(ctx, req) } func (ic *importClient) SetDownloadSpeedLimit( ctx context.Context, storeID uint64, req *import_sstpb.SetDownloadSpeedLimitRequest, ) (*import_sstpb.SetDownloadSpeedLimitResponse, error) { client, err := ic.GetImportClient(ctx, storeID) if err != nil { return nil, errors.Trace(err) } return client.SetDownloadSpeedLimit(ctx, req) } func (ic *importClient) IngestSST( ctx context.Context, storeID uint64, req *import_sstpb.IngestRequest, ) (*import_sstpb.IngestResponse, error) { client, err := ic.GetImportClient(ctx, storeID) if err != nil { return nil, errors.Trace(err) } return client.Ingest(ctx, req) } func (ic *importClient) MultiIngest( ctx context.Context, storeID uint64, req *import_sstpb.MultiIngestRequest,
client, err := ic.GetImportClient(ctx, storeID) if err != nil { return nil, errors.Trace(err) } return client.MultiIngest(ctx, req) } func (ic *importClient) GetImportClient( ctx context.Context, storeID uint64, ) (import_sstpb.ImportSSTClient, error) { ic.mu.Lock() defer ic.mu.Unlock() client, ok := ic.clients[storeID] if ok { return client, nil } store, err := ic.metaClient.GetStore(ctx, storeID) if err != nil { return nil, errors.Trace(err) } opt := grpc.WithInsecure() if ic.tlsConf != nil { opt = grpc.WithTransportCredentials(credentials.NewTLS(ic.tlsConf)) } addr := store.GetPeerAddress() if addr == "" { addr = store.GetAddress() } bfConf := backoff.DefaultConfig bfConf.MaxDelay = gRPCBackOffMaxDelay conn, err := grpc.DialContext( ctx, addr, opt, grpc.WithBlock(), grpc.FailOnNonTempDialError(true), grpc.WithConnectParams(grpc.ConnectParams{Backoff: bfConf}), grpc.WithKeepaliveParams(ic.keepaliveConf), ) if err != nil { return nil, errors.Trace(err) } client = import_sstpb.NewImportSSTClient(conn) ic.clients[storeID] = client return client, errors.Trace(err) } func (ic *importClient) SupportMultiIngest(ctx context.Context, stores []uint64) (bool, error) { for _, storeID := range stores { _, err := ic.MultiIngest(ctx, storeID, &import_sstpb.MultiIngestRequest{}) if err != nil { if s, ok := status.FromError(err); ok { if s.Code() == codes.Unimplemented { return false, nil } } return false, errors.Trace(err) } } return true, nil } // FileImporter used to import a file to TiKV. type FileImporter struct { metaClient SplitClient importClient ImporterClient backend *backuppb.StorageBackend rateLimit uint64 isRawKvMode bool rawStartKey []byte rawEndKey []byte supportMultiIngest bool } // NewFileImporter returns a new file importClient. func NewFileImporter( metaClient SplitClient, importClient ImporterClient, backend *backuppb.StorageBackend, isRawKvMode bool, rateLimit uint64, ) FileImporter { return FileImporter{ metaClient: metaClient, backend: backend, importClient: importClient, isRawKvMode: isRawKvMode, rateLimit: rateLimit, } } // CheckMultiIngestSupport checks whether all stores support multi-ingest func (importer *FileImporter) CheckMultiIngestSupport(ctx context.Context, pdClient pd.Client) error { allStores, err := conn.GetAllTiKVStores(ctx, pdClient, conn.SkipTiFlash) if err != nil { return errors.Trace(err) } storeIDs := make([]uint64, 0, len(allStores)) for _, s := range allStores { if s.State != metapb.StoreState_Up { continue } storeIDs = append(storeIDs, s.Id) } support, err := importer.importClient.SupportMultiIngest(ctx, storeIDs) if err != nil { return errors.Trace(err) } importer.supportMultiIngest = support log.L().Info("multi ingest support", zap.Bool("support", support)) return nil } // SetRawRange sets the range to be restored in raw kv mode. func (importer *FileImporter) SetRawRange(startKey, endKey []byte) error { if !importer.isRawKvMode { return errors.Annotate(berrors.ErrRestoreModeMismatch, "file importer is not in raw kv mode") } importer.rawStartKey = startKey importer.rawEndKey = endKey return nil } // getKeyRangeForFiles gets the maximum range on files. func (importer *FileImporter) getKeyRangeForFiles( files []*backuppb.File, rewriteRules *RewriteRules, ) ([]byte, []byte, error) { var ( startKey, endKey []byte start, end []byte err error ) for _, f := range files { if importer.isRawKvMode { start, end = f.GetStartKey(), f.GetEndKey() } else { start, end, err = rewriteFileKeys(f, rewriteRules) if err != nil { return nil, nil, errors.Trace(err) } } if len(startKey) == 0 || bytes.Compare(start, startKey) < 0 { startKey = start } if len(endKey) == 0 || bytes.Compare(endKey, end) < 0 { endKey = end } } log.Debug("rewrite file keys", logutil.Files(files), logutil.Key("startKey", startKey), logutil.Key("endKey", endKey)) return startKey, endKey, nil } // Import tries to import a file. // All rules must contain encoded keys. func (importer *FileImporter) Import( ctx context.Context, files []*backuppb.File, rewriteRules *RewriteRules, cipher *backuppb.CipherInfo, apiVersion kvrpcpb.APIVersion, ) error { start := time.Now() log.Debug("import file", logutil.Files(files)) // Rewrite the start key and end key of file to scan regions startKey, endKey, err := importer.getKeyRangeForFiles(files, rewriteRules) if err != nil { return errors.Trace(err) } err = utils.WithRetry(ctx, func() error { tctx, cancel := context.WithTimeout(ctx, importScanRegionTime) defer cancel() // Scan regions covered by the file range regionInfos, errScanRegion := PaginateScanRegion( tctx, importer.metaClient, startKey, endKey, ScanRegionPaginationLimit) if errScanRegion != nil { return errors.Trace(errScanRegion) } log.Debug("scan regions", logutil.Files(files), zap.Int("count", len(regionInfos))) // Try to download and ingest the file in every region regionLoop: for _, regionInfo := range regionInfos { info := regionInfo // Try to download file. downloadMetas, errDownload := importer.download(ctx, info, files, rewriteRules, cipher, apiVersion) if errDownload != nil { for _, e := range multierr.Errors(errDownload) { switch errors.Cause(e) { // nolint:errorlint case berrors.ErrKVRewriteRuleNotFound, berrors.ErrKVRangeIsEmpty: // Skip this region log.Warn("download file skipped", logutil.Files(files), logutil.Region(info.Region), logutil.Key("startKey", startKey), logutil.Key("endKey", endKey), logutil.Key("file-simple-start", files[0].StartKey), logutil.Key("file-simple-end", files[0].EndKey), logutil.ShortError(e)) continue regionLoop } } log.Error("download file failed", logutil.Files(files), logutil.Region(info.Region), logutil.Key("startKey", startKey), logutil.Key("endKey", endKey), logutil.ShortError(errDownload)) return errors.Trace(errDownload) } log.Debug("download file done", zap.String("file-sample", files[0].Name), zap.Stringer("take", time.Since(start)), logutil.Key("start", files[0].StartKey), logutil.Key("end", files[0].EndKey)) if errIngest := importer.ingest(ctx, info, downloadMetas); errIngest != nil { log.Error("ingest file failed", logutil.Files(files), logutil.SSTMetas(downloadMetas), logutil.Region(info.Region), zap.Error(errIngest)) return errors.Trace(errIngest) } } log.Debug("ingest file done", zap.String("file-sample", files[0].Name), zap.Stringer("take", time.Since(start))) for _, f := range files { summary.CollectSuccessUnit(summary.TotalKV, 1, f.TotalKvs) summary.CollectSuccessUnit(summary.TotalBytes, 1, f.TotalBytes) } return nil }, utils.NewImportSSTBackoffer()) return errors.Trace(err) } func (importer *FileImporter) setDownloadSpeedLimit(ctx context.Context, storeID uint64) error { req := &import_sstpb.SetDownloadSpeedLimitRequest{ SpeedLimit: importer.rateLimit, } _, err := importer.importClient.SetDownloadSpeedLimit(ctx, storeID, req) return errors.Trace(err) } func (importer *FileImporter) download( ctx context.Context, regionInfo *RegionInfo, files []*backuppb.File, rewriteRules *RewriteRules, cipher *backuppb.CipherInfo, apiVersion kvrpcpb.APIVersion, ) ([]*import_sstpb.SSTMeta, error) { var ( downloadMetas = make([]*import_sstpb.SSTMeta, 0, len(files)) remainFiles = files ) errDownload := utils.WithRetry(ctx, func() error { var e error for i, f := range remainFiles { var downloadMeta *import_sstpb.SSTMeta if importer.isRawKvMode { downloadMeta, e = importer.downloadRawKVSST(ctx, regionInfo, f, cipher, apiVersion) } else { downloadMeta, e = importer.downloadSST(ctx, regionInfo, f, rewriteRules, cipher) } failpoint.Inject("restore-storage-error", func(val failpoint.Value) { msg := val.(string) log.Debug("failpoint restore-storage-error injected.", zap.String("msg", msg)) e = errors.Annotate(e, msg) }) failpoint.Inject("restore-gRPC-error", func(_ failpoint.Value) { log.Warn("the connection to TiKV has been cut by a neko, meow :3") e = status.Error(codes.Unavailable, "the connection to TiKV has been cut by a neko, meow :3") }) if isDecryptSstErr(e) { log.Info("fail to decrypt when download sst, try again with no-crypt", logutil.File(f)) if importer.isRawKvMode { downloadMeta, e = importer.downloadRawKVSST(ctx, regionInfo, f, nil, apiVersion) } else { downloadMeta, e = importer.downloadSST(ctx, regionInfo, f, rewriteRules, nil) } } if e != nil { remainFiles = remainFiles[i:] return errors.Trace(e) } downloadMetas = append(downloadMetas, downloadMeta) } return nil }, utils.NewDownloadSSTBackoffer()) return downloadMetas, errDownload } func (importer *FileImporter) downloadSST( ctx context.Context, regionInfo *RegionInfo, file *backuppb.File, rewriteRules *RewriteRules, cipher *backuppb.CipherInfo, ) (*import_sstpb.SSTMeta, error) { uid := uuid.New() id := uid[:] // Get the rewrite rule for the file. fileRule := findMatchedRewriteRule(file, rewriteRules) if fileRule == nil { return nil, errors.Trace(berrors.ErrKVRewriteRuleNotFound) } rule := import_sstpb.RewriteRule{ OldKeyPrefix: encodeKeyPrefix(fileRule.GetOldKeyPrefix()), NewKeyPrefix: encodeKeyPrefix(fileRule.GetNewKeyPrefix()), } sstMeta := GetSSTMetaFromFile(id, file, regionInfo.Region, &rule) req := &import_sstpb.DownloadRequest{ Sst: sstMeta, StorageBackend: importer.backend, Name: file.GetName(), RewriteRule: rule, CipherInfo: cipher, } log.Debug("download SST", logutil.SSTMeta(&sstMeta), logutil.File(file), logutil.Region(regionInfo.Region), logutil.Leader(regionInfo.Leader), ) var atomicResp atomic.Value eg, ectx := errgroup.WithContext(ctx) for _, p := range regionInfo.Region.GetPeers() { peer := p eg.Go(func() error { resp, err := importer.importClient.DownloadSST(ectx, peer.GetStoreId(), req) if err != nil { return errors.Trace(err) } if resp.GetError() != nil { return errors.Annotate(berrors.ErrKVDownloadFailed, resp.GetError().GetMessage()) } if resp.GetIsEmpty() { return errors.Trace(berrors.ErrKVRangeIsEmpty) } log.Debug("download from peer", logutil.Region(regionInfo.Region), logutil.Peer(peer), logutil.Key("resp-range-start", resp.Range.Start), logutil.Key("resp-range-end", resp.Range.Start), zap.Bool("resp-isempty", resp.IsEmpty), zap.Uint32("resp-crc32", resp.Crc32), ) atomicResp.Store(resp) return nil }) } if err := eg.Wait(); err != nil { return nil, err } downloadResp := atomicResp.Load().(*import_sstpb.DownloadResponse) sstMeta.Range.Start = truncateTS(downloadResp.Range.GetStart()) sstMeta.Range.End = truncateTS(downloadResp.Range.GetEnd()) return &sstMeta, nil } func (importer *FileImporter) downloadRawKVSST( ctx context.Context, regionInfo *RegionInfo, file *backuppb.File, cipher *backuppb.CipherInfo, apiVersion kvrpcpb.APIVersion, ) (*import_sstpb.SSTMeta, error) { uid := uuid.New() id := uid[:] // Empty rule var rule import_sstpb.RewriteRule sstMeta := GetSSTMetaFromFile(id, file, regionInfo.Region, &rule) // Cut the SST file's range to fit in the restoring range. if bytes.Compare(importer.rawStartKey, sstMeta.Range.GetStart()) > 0 { sstMeta.Range.Start = importer.rawStartKey } if len(importer.rawEndKey) > 0 && (len(sstMeta.Range.GetEnd()) == 0 || bytes.Compare(importer.rawEndKey, sstMeta.Range.GetEnd()) <= 0) { sstMeta.Range.End = importer.rawEndKey sstMeta.EndKeyExclusive = true } if bytes.Compare(sstMeta.Range.GetStart(), sstMeta.Range.GetEnd()) > 0 { return nil, errors.Trace(berrors.ErrKVRangeIsEmpty) } req := &import_sstpb.DownloadRequest{ Sst: sstMeta, StorageBackend: importer.backend, Name: file.GetName(), RewriteRule: rule, IsRawKv: true, CipherInfo: cipher, } log.Debug("download SST", logutil.SSTMeta(&sstMeta), logutil.Region(regionInfo.Region)) var atomicResp atomic.Value eg, ectx := errgroup.WithContext(ctx) for _, p := range regionInfo.Region.GetPeers() { peer := p eg.Go(func() error { resp, err := importer.importClient.DownloadSST(ectx, peer.GetStoreId(), req) if err != nil { return errors.Trace(err) } if resp.GetError() != nil { return errors.Annotate(berrors.ErrKVDownloadFailed, resp.GetError().GetMessage()) } if resp.GetIsEmpty() { return errors.Trace(berrors.ErrKVRangeIsEmpty) } atomicResp.Store(resp) return nil }) } if err := eg.Wait(); err != nil { return nil, err } downloadResp := atomicResp.Load().(*import_sstpb.DownloadResponse) sstMeta.Range.Start = downloadResp.Range.GetStart() sstMeta.Range.End = downloadResp.Range.GetEnd() sstMeta.ApiVersion = apiVersion return &sstMeta, nil } func (importer *FileImporter) ingest( ctx context.Context, info *RegionInfo, downloadMetas []*import_sstpb.SSTMeta, ) error { for { ingestResp, errIngest := importer.ingestSSTs(ctx, downloadMetas, info) if errIngest != nil { return errors.Trace(errIngest) } errPb := ingestResp.GetError() switch { case errPb == nil: return nil case errPb.NotLeader != nil: // If error is `NotLeader`, update the region info and retry var newInfo *RegionInfo if newLeader := errPb.GetNotLeader().GetLeader(); newLeader != nil { newInfo = &RegionInfo{ Leader: newLeader, Region: info.Region, } } else { for { // Slow path, get region from PD newInfo, errIngest = importer.metaClient.GetRegion( ctx, info.Region.GetStartKey()) if errIngest != nil { return errors.Trace(errIngest) } if newInfo != nil { break } // do not get region info, wait a second and GetRegion() again. log.Warn("get region by key return nil", logutil.Region(info.Region)) time.Sleep(time.Second) } } if !checkRegionEpoch(newInfo, info) { return errors.Trace(berrors.ErrKVEpochNotMatch) } log.Debug("ingest sst returns not leader error, retry it", logutil.Region(info.Region), zap.Stringer("newLeader", newInfo.Leader)) info = newInfo case errPb.EpochNotMatch != nil: // TODO handle epoch not match error // 1. retry download if needed // 2. retry ingest return errors.Trace(berrors.ErrKVEpochNotMatch) case errPb.KeyNotInRegion != nil: return errors.Trace(berrors.ErrKVKeyNotInRegion) default: // Other errors like `ServerIsBusy`, `RegionNotFound`, etc. should be retryable return errors.Annotatef(berrors.ErrKVIngestFailed, "ingest error %s", errPb) } } } func (importer *FileImporter) ingestSSTs( ctx context.Context, sstMetas []*import_sstpb.SSTMeta, regionInfo *RegionInfo, ) (*import_sstpb.IngestResponse, error) { leader := regionInfo.Leader if leader == nil { leader = regionInfo.Region.GetPeers()[0] } reqCtx := &kvrpcpb.Context{ RegionId: regionInfo.Region.GetId(), RegionEpoch: regionInfo.Region.GetRegionEpoch(), Peer: leader, } if !importer.supportMultiIngest { // TODO: not sure we need this check if len(sstMetas) != 1 { panic("do not support batch ingest") } req := &import_sstpb.IngestRequest{ Context: reqCtx, Sst: sstMetas[0], } log.Debug("ingest SST", logutil.SSTMeta(sstMetas[0]), logutil.Leader(leader)) resp, err := importer.importClient.IngestSST(ctx, leader.GetStoreId(), req) return resp, errors.Trace(err) } req := &import_sstpb.MultiIngestRequest{ Context: reqCtx, Ssts: sstMetas, } log.Debug("ingest SSTs", logutil.SSTMetas(sstMetas), logutil.Leader(leader)) resp, err := importer.importClient.MultiIngest(ctx, leader.GetStoreId(), req) return resp, errors.Trace(err) } func isDecryptSstErr(err error) bool { return err != nil && strings.Contains(err.Error(), "Engine Engine") && strings.Contains(err.Error(), "Corruption: Bad table magic number") }
) (*import_sstpb.IngestResponse, error) {
NameScreen.js
import React, { useEffect, useState } from "react"; import FormScreen from "../../components/registration/FormScreen"; import routes from "../../navigation/routes"; import TextInput from "../../components/TextInput"; import Text from "../../components/typography/Text"; import { screen } from "../../config/dimensions"; function
({ navigation }) { const [username, setUsername] = useState(false); const [disabled, setDisabled] = useState(false); const handleActive = (username) => { if (username.username) { setDisabled(true); return; } setDisabled(false); }; useEffect(() => { handleActive(username); }, [username]); return ( <FormScreen title="My name is" isActive={disabled} onPress={() => navigation.navigate(routes.REGISTERPRONOUN, { ...username }) } pagination={require("../../assets/pagination/2.png")} > <TextInput placeholder={"Name"} onChangeText={(username) => setUsername({ username })} icon="account" value={username["username"]} style={{ marginBottom: 12 }} width={screen.width * 0.83} /> <Text style={{ lineHeight: 25, marginBottom: 120, alignSelf: "center" }}> The chosen name will appear in you profile </Text> </FormScreen> ); } export default NameScreen;
NameScreen
main.go
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START gameservices_generated_gaming_apiv1_GameServerDeploymentsClient_ListGameServerDeployments] package main import ( "context" gaming "cloud.google.com/go/gaming/apiv1" "google.golang.org/api/iterator" gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" ) func main() { // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" // import "google.golang.org/api/iterator" ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } req := &gamingpb.ListGameServerDeploymentsRequest{ // TODO: Fill request struct fields. } it := c.ListGameServerDeployments(ctx, req) for { resp, err := it.Next() if err == iterator.Done
if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp } } // [END gameservices_generated_gaming_apiv1_GameServerDeploymentsClient_ListGameServerDeployments]
{ break }
struct_field_simple.rs
// This file is automatically generated from // frameworks/rs/tests/java_api/RSUnitTests/RSUnitTests.py
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "shared.rsh" struct Simple { int I; long L; }; struct Simple simple; void checkSimple(int argI, long argL) { bool failed = false; rsDebug("argI ", argI); rsDebug("simple.I ", simple.I); rsDebug("argL.lo ", (unsigned)argL & ~0U); rsDebug("simple.L.lo", (unsigned)simple.L & ~0U); rsDebug("argL.hi ", (unsigned)((ulong)argL >> 32)); rsDebug("simple.L.hi", (unsigned)((ulong)simple.L >> 32)); _RS_ASSERT(simple.I == argI); _RS_ASSERT(simple.L == argL); if (failed) { rsDebug("struct_field_simple FAILED", 0); rsSendToClientBlocking(RS_MSG_TEST_FAILED); } else { rsDebug("struct_field_simple PASSED", 0); rsSendToClientBlocking(RS_MSG_TEST_PASSED); } }
signal_windows.rs
// std imports use std::time::Duration; // local imports use crate::error::*; // --- pub struct SignalHandler {} impl SignalHandler { pub fn
<F>(_: usize, _: Duration, f: F) -> Result<()> where F: FnOnce() -> Result<()>, { f() } }
run
ListOrganizationsExceptionsUnion.ts
import { InvalidParameterException } from "./InvalidParameterException";
export type ListOrganizationsExceptionsUnion = InvalidParameterException;
app-routing.module.ts
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ObjectiveList } from './objectives/objective-list/objective-list.component'
{ path: 'objectives', component: ObjectiveList } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
const routes: Routes = [ { path: '', redirectTo: '/objectives', pathMatch: 'full' },
util.py
import tensorflow as tf import numpy as np def switch_case_cond(cases, default_case): if cases: condition, effect = cases[0] return tf.cond(condition, effect, lambda: switch_case_cond(cases[1:], default_case)) return default_case() def switch_case_where(cases, default_case): if cases: condition, effect = cases[0] return tf.where(condition, effect, switch_case_where(cases[1:], default_case)) return default_case def np_dtype(tf_dtype): if tf_dtype == tf.float32: return np.float32 if tf_dtype == tf.float64: return np.float64 raise Exception('Unsupported dtype') def f32_to_dtype(x, dtype): if dtype == tf.float32: return x return tf.cast(x, dtype) def as_tuple(x): '''Formats x as a tuple. If x is already a tuple returns it as is, otherwise returns a 1-tuple containing x.''' if isinstance(x, tuple):
return x else: return (x,) def for_each(x, func): '''Runs 'func' for x, or each item of x if x is a tuple. Returns the results in the same format.''' if isinstance(x, tuple): return tuple((func(s) for s in x)) else: return func(x) def for_tuple(x, func): '''Runs 'func' for as_tuple(x). Returns the results in the original format. Assumes 'func' returns tuple when given tuple.''' if isinstance(x, tuple): return func(x) else: return func(as_tuple(x))[0]
callback.py
"Callbacks provides extensibility to the `basic_train` loop. See `train` for examples of custom callbacks." from .data import * from .torch_core import * __all__ = ['Callback', 'CallbackHandler', 'OptimWrapper', 'SmoothenValue', 'Stepper', 'annealing_cos', 'CallbackList', 'annealing_exp', 'annealing_linear', 'annealing_no', 'annealing_poly', 'do_annealing_poly'] class OptimWrapper(): "Basic wrapper around an optimizer to simplify HP changes." def __init__(self, opt:optim.Optimizer, wd:Floats=0., true_wd:bool=False, bn_wd:bool=True): self.opt,self.true_wd,self.bn_wd = opt,true_wd,bn_wd self.opt_keys = list(self.opt.param_groups[0].keys()) self.opt_keys.remove('params') self.read_defaults() self.wd = wd @classmethod def create(cls, opt_fn:Union[type,Callable], lr:Union[float,Tuple,List], layer_groups:ModuleList, **kwargs:Any)->optim.Optimizer: "Create an optim.Optimizer from `opt_fn` with `lr`. Set lr on `layer_groups`." split_groups = split_bn_bias(layer_groups) opt = opt_fn([{'params': trainable_params(l), 'lr':0} for l in split_groups]) opt = cls(opt, **kwargs) opt.lr = listify(lr, layer_groups) return opt def __repr__(self)->str: return f'OptimWrapper over {repr(self.opt)}.\nTrue weight decay: {self.true_wd}' #Pytorch optimizer methods def step(self)->None: "Set weight decay and step optimizer." # weight decay outside of optimizer step (AdamW) if self.true_wd: for lr,wd,pg1,pg2 in zip(self._lr,self._wd,self.opt.param_groups[::2],self.opt.param_groups[1::2]): for p in pg1['params']: p.data.mul_(1 - wd*lr) if self.bn_wd: for p in pg2['params']: p.data.mul_(1 - wd*lr) self.set_val('weight_decay', listify(0, self._wd)) self.opt.step() def zero_grad(self)->None: "Clear optimizer gradients." self.opt.zero_grad() #Hyperparameters as properties @property def lr(self)->float: "Get learning rate." return self._lr[-1] @lr.setter def lr(self, val:float)->None: "Set learning rate." self._lr = self.set_val('lr', listify(val, self._lr)) @property def mom(self)->float: "Get momentum." return self._mom[-1] @mom.setter def mom(self, val:float)->None: "Set momentum." if 'momentum' in self.opt_keys: self.set_val('momentum', listify(val, self._mom)) elif 'betas' in self.opt_keys: self.set_val('betas', (listify(val, self._mom), self._beta)) self._mom = listify(val, self._mom) @property def beta(self)->float: "Get beta (or alpha as makes sense for given optimizer)." return None if self._beta is None else self._beta[-1] @beta.setter def beta(self, val:float)->None: "Set beta (or alpha as makes sense for given optimizer)." if val is None: return if 'betas' in self.opt_keys: self.set_val('betas', (self._mom, listify(val, self._beta))) elif 'alpha' in self.opt_keys: self.set_val('alpha', listify(val, self._beta)) self._beta = listify(val, self._beta) @property def wd(self)->float: "Get weight decay." return self._wd[-1] @wd.setter def wd(self, val:float)->None: "Set weight decay." if not self.true_wd: self.set_val('weight_decay', listify(val, self._wd), bn_groups=self.bn_wd) self._wd = listify(val, self._wd) #Helper functions def read_defaults(self)->None: "Read the values inside the optimizer for the hyper-parameters." self._beta = None if 'lr' in self.opt_keys: self._lr = self.read_val('lr') if 'momentum' in self.opt_keys: self._mom = self.read_val('momentum') if 'alpha' in self.opt_keys: self._beta = self.read_val('alpha') if 'betas' in self.opt_keys: self._mom,self._beta = self.read_val('betas') if 'weight_decay' in self.opt_keys: self._wd = self.read_val('weight_decay') def set_val(self, key:str, val:Any, bn_groups:bool=True)->Any: "Set the values inside the optimizer dictionary at the key." if is_tuple(val): val = [(v1,v2) for v1,v2 in zip(*val)] for v,pg1,pg2 in zip(val,self.opt.param_groups[::2],self.opt.param_groups[1::2]): pg1[key] = v if bn_groups: pg2[key] = v return val def read_val(self, key:str) -> Union[List[float],Tuple[List[float],List[float]]]: "Read a hyperparameter key in the optimizer dictionary." val = [pg[key] for pg in self.opt.param_groups[::2]] if is_tuple(val[0]): val = [o[0] for o in val], [o[1] for o in val] return val class Callback(): "Base class for callbacks that want to record values, dynamically change learner params, etc." _order=0 def on_train_begin(self, **kwargs:Any)->None: "To initialize constants in the callback." pass def on_epoch_begin(self, **kwargs:Any)->None: "At the beginning of each epoch." pass def on_batch_begin(self, **kwargs:Any)->None: "Set HP before the step is done. Returns xb, yb (which can allow us to modify the input at that step if needed)." pass def on_loss_begin(self, **kwargs:Any)->None: "Called after forward pass but before loss has been computed. Returns the output (which can allow us to modify it)." pass def on_backward_begin(self, **kwargs:Any)->None: """Called after the forward pass and the loss has been computed, but before backprop. Returns the loss (which can allow us to modify it, for instance for reg functions)""" pass def on_backward_end(self, **kwargs:Any)->None: "Called after backprop but before optimizer step. Useful for true weight decay in AdamW." pass def on_step_end(self, **kwargs:Any)->None: "Called after the step of the optimizer but before the gradients are zeroed." pass def on_batch_end(self, **kwargs:Any)->None: "Called at the end of the batch." pass def on_epoch_end(self, **kwargs:Any)->bool: "Called at the end of an epoch." return False def on_train_end(self, **kwargs:Any)->None: "Useful for cleaning up things and saving files/models." pass class SmoothenValue(): "Create a smooth moving average for a value (loss, etc)." def __init__(self, beta:float): "Create smoother for value, beta should be 0<beta<1." self.beta,self.n,self.mov_avg = beta,0,0 def add_value(self, val:float)->None: "Add current value to calculate updated smoothed value." self.n += 1 self.mov_avg = self.beta * self.mov_avg + (1 - self.beta) * val self.smooth = self.mov_avg / (1 - self.beta ** self.n) CallbackList = Collection[Callback] def _get_init_state(): return {'epoch':0, 'iteration':0, 'num_batch':0} @dataclass class CallbackHandler(): "Manage all of the registered callback objects, smoothing loss by momentum `beta`." callbacks:CallbackList beta:float=0.98 def __post_init__(self)->None: "Initialize smoother and learning stats." self.callbacks = sorted(self.callbacks, key=lambda o: getattr(o, '_order', 0)) self.smoothener = SmoothenValue(self.beta) self.state_dict:Dict[str,Union[int,float,Tensor]]=_get_init_state() def __call__(self, cb_name, **kwargs)->None: "Call through to all of the `CallbakHandler` functions." return [getattr(cb, f'on_{cb_name}')(**self.state_dict, **kwargs) for cb in self.callbacks] def
(self, epochs:int, pbar:PBar, metrics:MetricFuncList)->None: "About to start learning." self.state_dict = _get_init_state() self.state_dict['n_epochs'],self.state_dict['pbar'],self.state_dict['metrics'] = epochs,pbar,metrics self('train_begin') def on_epoch_begin(self)->None: "Handle new epoch." self.state_dict['num_batch'] = 0 self('epoch_begin') def on_batch_begin(self, xb:Tensor, yb:Tensor)->None: "Handle new batch `xb`,`yb`." self.state_dict['last_input'], self.state_dict['last_target'] = xb, yb for cb in self.callbacks: a = cb.on_batch_begin(**self.state_dict) if a is not None: self.state_dict['last_input'], self.state_dict['last_target'] = a return self.state_dict['last_input'], self.state_dict['last_target'] def on_loss_begin(self, out:Tensor)->None: "Handle start of loss calculation with model output `out`." self.state_dict['last_output'] = out for cb in self.callbacks: a = cb.on_loss_begin(**self.state_dict) if a is not None: self.state_dict['last_output'] = a return self.state_dict['last_output'] def on_backward_begin(self, loss:Tensor)->None: "Handle gradient calculation on `loss`." self.smoothener.add_value(loss.detach()) self.state_dict['last_loss'], self.state_dict['smooth_loss'] = loss, self.smoothener.smooth for cb in self.callbacks: a = cb.on_backward_begin(**self.state_dict) if a is not None: self.state_dict['last_loss'] = a return self.state_dict['last_loss'] def on_backward_end(self)->None: "Handle end of gradient calculation." self('backward_end') def on_step_end(self)->None: "Handle end of optimization step." self('step_end') def on_batch_end(self, loss:Tensor)->None: "Handle end of processing one batch with `loss`." self.state_dict['last_loss'] = loss stop = np.any(self('batch_end')) self.state_dict['iteration'] += 1 self.state_dict['num_batch'] += 1 return stop def on_epoch_end(self, val_metrics:MetricsList)->bool: "Epoch is done, process `val_metrics`." self.state_dict['last_metrics'] = val_metrics stop = np.any(self('epoch_end')) self.state_dict['epoch'] += 1 return stop def on_train_end(self, exception:Union[bool,Exception])->None: "Handle end of training, `exception` is an `Exception` or False if no exceptions during training." self('train_end', exception=exception) def annealing_no(start:Number, end:Number, pct:float)->Number: "No annealing, always return `start`." return start def annealing_linear(start:Number, end:Number, pct:float)->Number: "Linearly anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start + pct * (end-start) def annealing_exp(start:Number, end:Number, pct:float)->Number: "Exponentially anneal from `start` to `end` as pct goes from 0.0 to 1.0." return start * (end/start) ** pct def annealing_cos(start:Number, end:Number, pct:float)->Number: "Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0." cos_out = np.cos(np.pi * pct) + 1 return end + (start-end)/2 * cos_out def do_annealing_poly(start:Number, end:Number, pct:float, degree:Number)->Number: "Helper function for `anneal_poly`." return end + (start-end) * (1-pct)**degree def annealing_poly(degree:Number)->Number: "Anneal polynomically from `start` to `end` as pct goes from 0.0 to 1.0." return functools.partial(do_annealing_poly, degree=degree) class Stepper(): "Used to \"step\" from start,end (`vals`) over `n_iter` iterations on a schedule defined by `func`" def __init__(self, vals:StartOptEnd, n_iter:int, func:Optional[AnnealFunc]=None): self.start,self.end = (vals[0],vals[1]) if is_tuple(vals) else (vals,0) self.n_iter = n_iter if func is None: self.func = annealing_linear if is_tuple(vals) else annealing_no else: self.func = func self.n = 0 def step(self)->Number: "Return next value along annealed schedule." self.n += 1 return self.func(self.start, self.end, self.n/self.n_iter) @property def is_done(self)->bool: "Schedule completed." return self.n >= self.n_iter
on_train_begin
MultisigTransactions.js
/* * Wallet API * # Introduction Wallet API는 클레이튼 계정을 만들어 관리하고 트랜잭션을 전송하는 API입니다. Wallet API로 Klaytn 계정을 만들면 여러분은 개인키를 따로 관리할 필요가 없습니다. Wallet API는 BApp을 위해 Klaytn 계정 개인키를 안전하게 보관하는 지갑을 제공합니다. Wallet API 사용에 관한 자세한 내용은 [튜토리얼](https://docs.klaytnapi.com/v/ko/tutorial)을 확인하십시오. Wallet API는 크게 Klaytn 계정을 만들고 관리하는 Account 파트와 여러 종류의 트랜잭션을 전송하는 Transaction 파트로 나뉩니다. Wallet API는 Klaytn 계정을 생성, 삭제, 모니터링하고 계정을 다중 서명 계정(Multisig 계정)으로 업데이트하며 KAS에 등록된 모든 계정의 개인키를 관리합니다. 또 Wallet API는 트랜잭션을 만들어 Klaytn에 전송합니다. 이 트랜잭션에는 다중 서명 계정이 보내는 트랜잭션도 포함됩니다. 다중 서명 시 임계값\\(Threshold\\)을 만족하면 트랜잭션은 Klaytn에 자동으로 전송됩니다. 다중 서명에 관한 자세한 내용은 [다음](https://docs.klaytnapi.com/v/ko/tutorial)을 확인하십시오. 트랜잭션은 크게 기본 트랜잭션과 수수료 대납 트랜잭션으로 나뉩니다. 수수료 대납 트랜잭션은 크게 글로벌 수수료 대납 트랜잭션과 사용자 수수료 대납 트랜잭션으로 나뉩니다. 글로벌 수수료 대납 트랜잭션은 Ground X의 KAS 계정에서 트랜잭션 수수료를 일단 대납해주고 나중에 여러분에게 이 수수료를 청구하는 방식입니다. 사용자 수수료 대납 트랜잭션은 여러분이 직접 트랜잭션 수수료를 대납하는 계정을 만들고, 트랜잭션을 보낼 때 이 대납 계정이 트랜잭션 수수료를 납부하도록 하는 방식입니다. Wallet API는 아래와 같은 기능 및 제약사항을 갖고 있습니다. | Version | Item | Description | | :--- | :--- | :--- | | 2.0 | 제약사항 | Cypress(Mainnet), Baobab(Testnet) 지원\\(Service Chain 미지원\\) | | | | 외부 관리키에 대한 계정 관리 미지원 | | | | RLP 인코딩된 트랜잭션의 다중 서명 미지원 | | | 계정관리 | 계정 생성, 조회, 삭제 | | | | 다중 서명 계정 업데이트 | | | 트랜잭션 관리 | [Basic](https://ko.docs.klaytn.com/klaytn/design/transactions/basic) 트랜잭션 생성 및 전송 | | | | [FeeDelegatedWithRatio](https://ko.docs.klaytn.com/klaytn/design/transactions/partial-fee-delegation) 트랜잭션 생성 및 전송 | | | | RLP 인코딩된 트랜잭션\\([Legacy](https://ko.docs.klaytn.com/klaytn/design/transactions/basic#txtypelegacytransaction), [Basic](https://ko.docs.klaytn.com/klaytn/design/transactions/basic), [FeeDelegatedWithRatio](https://ko.docs.klaytn.com/klaytn/design/transactions/partial-fee-delegation)\\) 생성 및 전송 | | | | 다중 서명 트랜잭션 관리 및 전송 | | | 관리자 | 리소스 풀 관리\\(생성, 풀 조회, 삭제, 계정 조회\\) | # Error Codes ## 400: Bad Request | Code | Messages | | --- | --- | | 1061010 | data don't exist 1061510 | account has been already deleted or disabled 1061511 | account has been already deleted or enabled 1061512 | account is invalid to sign the transaction; 0xc9bFDDabf2c38396b097C8faBE9151955413995D</br>account is invalid to sign the transaction; 0x35Cc4921B17Dfa67a58B93c9F8918f823e58b77e 1061515 | the requested account must be a legacy account; if the account is multisig account, use `PUT /v2/tx/{fd|fd-user}/account` API for multisig transaction and /v2/multisig/_**_/_** APIs 1061607 | it has to start with '0x' and allows [0-9a-fA-F]; input</br>it has to start with '0x' and allows [0-9a-fA-F]; transaction-id 1061608 | cannot be empty or zero value; to</br>cannot be empty or zero value; input 1061609 | it just allow Klaytn address form; to 1061903 | failed to decode account keys 1061905 | failed to get feepayer 1061912 | rlp value and request value are not same; feeRatio</br>rlp value and request value are not same; feePayer 1061914 | already submitted transaction. Confirm transaction hash; 0xb9612ec6ec39bfd3f2841daa7ab062fc94cf33f23503606c979b2f81e50b2cb1 1061917 | AccountKeyLegacy type is not supported in AccountKeyRoleBased type 1061918 | it just allow (Partial)FeeDelegation transaction type 1061919 | PartialFeeDelegation transaction must set fee ratio to non-zero value 1061920 | FeeDelegation transaction cannot set fee ratio, use PartialFeeDelegation transaction type 1061921 | it just allow Basic transaction type 1065000 | failed to retrieve a transaction from klaytn node 1065001 | failed to send a raw transaction to klaytn node; -32000::insufficient funds of the sender for value </br>failed to send a raw transaction to klaytn node; -32000::not a program account (e.g., an account having code and storage)</br>failed to send a raw transaction to klaytn node; -32000::nonce too low</br>failed to send a raw transaction to klaytn node; -32000::insufficient funds of the fee payer for gas * price 1065100 | failed to get an account from AMS</br>failed to get an account from AMS; account key corrupted. can not use this account 1065102 | account key corrupted. can not use this account 1616 | feeration must be between 1 and 99; feeRatio 1918 | it just allow (Partial)FeeDelegation transaction type | * * OpenAPI spec version: 1.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * * Swagger Codegen version: 2.4.15 * * Do not edit the class manually. * */ ;(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['../../ApiClient', '../model/PendedTransaction'], factory) } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../../ApiClient'), require('./PendedTransaction')) } else { // Browser globals (root is window) if (!root.WalletApi) { root.WalletApi = {} } root.WalletApi.MultisigTransactions = factory(root.WalletApi.ApiClient, root.WalletApi.PendedTransaction) } })(this, function(ApiClient, PendedTransaction) { /** * The MultisigTransactions model module. * @module model/MultisigTransactions * @version 1.0 */ /** * Constructs a new <code>MultisigTransactions</code>. * 보류중인 트랜잭션 목록 * @alias module:model/MultisigTransactions * @class * @param cursor {String} 마지막으로 검색된 커서의 정보 */ const MultisigTransactions = function(cursor) { this.cursor = cursor } /** * Constructs a <code>MultisigTransactions</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/MultisigTransactions} obj Optional instance to populate. * @return {module:model/MultisigTransactions} The populated <code>MultisigTransactions</code> instance.
if (data.hasOwnProperty('cursor')) obj.cursor = ApiClient.convertToType(data.cursor, 'String') if (data.hasOwnProperty('items')) obj.items = ApiClient.convertToType(data.items, [PendedTransaction]) } return obj } /** * 마지막으로 검색된 커서의 정보 * @member {String} cursor */ MultisigTransactions.prototype.cursor = undefined /** * @member {Array.<module:model/PendedTransaction>} items */ MultisigTransactions.prototype.items = undefined return MultisigTransactions })
*/ MultisigTransactions.constructFromObject = function(data, obj) { if (data) { obj = obj || new MultisigTransactions()
main.go
package main import ( jwriter "github.com/CosmWasm/tinyjson/jwriter" "github.com/pion/explainer" ) //nolint: deadcode, unused, golint type ( Result = explainer.Result SessionDetails = explainer.SessionDetails PeerDetails = explainer.PeerDetails ) const ( bufferSize int = 500000 ) //nolint: unused, golint, gochecknoglobals var ( buffer [bufferSize]byte peerConnectionExplainer explainer.PeerConnectionExplainer ) func main() {} //export getWasmMemoryBufferOffset func getWasmMemoryBufferOffset() *[bufferSize]byte { //nolint: deadcode, unused return &buffer } func maybeInitExplainer() { //nolint: deadcode, unused if peerConnectionExplainer == nil { peerConnectionExplainer = explainer.NewPeerConnectionExplainer() } } // SetLocalDescription updates the PeerConnectionExplainer with the provided SessionDescription //export SetLocalDescription func SetLocalDescription(length int) { //nolint: unused, deadcode maybeInitExplainer() peerConnectionExplainer.SetLocalDescription(string(buffer[:length])) } // SetRemoteDescription updates the PeerConnectionExplainer with the provided SessionDescription //export SetRemoteDescription func SetRemoteDescription(length int) { //nolint: deadcode, unused, golint maybeInitExplainer() peerConnectionExplainer.SetRemoteDescription(string(buffer[:length])) } // Explain returns the result of the current PeerConnectionExplainer. //export Explain func Explain() int { //nolint: deadcode, unused maybeInitExplainer() w := jwriter.Writer{} tinyjsonA669327EncodeGithubComPionExplainer1(&w, peerConnectionExplainer.Explain()) if w.Error != nil { return 0 } return copy(buffer[:], w.Buffer.BuildBytes()) } // GetLocalDescription returns the current SDP we are using from SetLocalDescription //export GetLocalDescription func
() int { //nolint: deadcode, unused maybeInitExplainer() return copy(buffer[:], peerConnectionExplainer.GetLocalDescription()) } // GetRemoteDescription returns the current SDP we are using from GetRemoteDescription //export GetRemoteDescription func GetRemoteDescription() int { //nolint: deadcode, unused maybeInitExplainer() return copy(buffer[:], peerConnectionExplainer.GetRemoteDescription()) }
GetLocalDescription
describe_user_flow_statistics.go
package smartag //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // DescribeUserFlowStatistics invokes the smartag.DescribeUserFlowStatistics API synchronously // api document: https://help.aliyun.com/api/smartag/describeuserflowstatistics.html func (client *Client) DescribeUserFlowStatistics(request *DescribeUserFlowStatisticsRequest) (response *DescribeUserFlowStatisticsResponse, err error) { response = CreateDescribeUserFlowStatisticsResponse() err = client.DoAction(request, response) return } // DescribeUserFlowStatisticsWithChan invokes the smartag.DescribeUserFlowStatistics API asynchronously // api document: https://help.aliyun.com/api/smartag/describeuserflowstatistics.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) DescribeUserFlowStatisticsWithChan(request *DescribeUserFlowStatisticsRequest) (<-chan *DescribeUserFlowStatisticsResponse, <-chan error) { responseChan := make(chan *DescribeUserFlowStatisticsResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.DescribeUserFlowStatistics(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // DescribeUserFlowStatisticsWithCallback invokes the smartag.DescribeUserFlowStatistics API asynchronously // api document: https://help.aliyun.com/api/smartag/describeuserflowstatistics.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) DescribeUserFlowStatisticsWithCallback(request *DescribeUserFlowStatisticsRequest, callback func(response *DescribeUserFlowStatisticsResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *DescribeUserFlowStatisticsResponse var err error defer close(result) response, err = client.DescribeUserFlowStatistics(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // DescribeUserFlowStatisticsRequest is the request struct for api DescribeUserFlowStatistics type DescribeUserFlowStatisticsRequest struct { *requests.RpcRequest ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` OwnerAccount string `position:"Query" name:"OwnerAccount"` SmartAGId string `position:"Query" name:"SmartAGId"` StatisticsDate string `position:"Query" name:"StatisticsDate"` UserNames *[]string `position:"Query" name:"UserNames" type:"Repeated"` OwnerId requests.Integer `position:"Query" name:"OwnerId"` } // DescribeUserFlowStatisticsResponse is the response struct for api DescribeUserFlowStatistics type DescribeUserFlowStatisticsResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` SagStatistics SagStatisticsInDescribeUserFlowStatistics `json:"SagStatistics" xml:"SagStatistics"` } // CreateDescribeUserFlowStatisticsRequest creates a request to invoke DescribeUserFlowStatistics API func CreateDescribeUserFlowStatisticsRequest() (request *DescribeUserFlowStatisticsRequest) { request = &DescribeUserFlowStatisticsRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("Smartag", "2018-03-13", "DescribeUserFlowStatistics", "smartag", "openAPI") return } // CreateDescribeUserFlowStatisticsResponse creates a response to parse from DescribeUserFlowStatistics response func CreateDescribeUserFlowStatisticsResponse() (response *DescribeUserFlowStatisticsResponse) { response = &DescribeUserFlowStatisticsResponse{ BaseResponse: &responses.BaseResponse{}, }
return }
fileCrash.ts
import IArchive from '../interfaces/IArchive'; import IProtection from '../interfaces/IProtection'; const pickle = require('chromium-pickle-js'); export default class
implements IProtection { private readonly target: string; private readonly size: number; constructor(target: string, size?: number) { this.target = target; this.size = size || -1000; } apply(archive: IArchive): IArchive { const header = archive.header; if (header.files.hasOwnProperty(this.target)) { header.files[this.target].size = this.size; const headerPickle = pickle.createEmpty(); headerPickle.writeString(JSON.stringify(header)) const headerSize = headerPickle.toBuffer().length; return { headerSize, header, } } throw new Error(`${this.target} not found in archive!`) } }
FileCrash
relationship.py
# -*- coding: utf-8 -*- """ 获取用户关注 """ import json import redis from scrapy_redis.spiders import RedisSpider from ..items import Relationship from .bos_filter import RedisDB, BosFilter class RelationshipSpider(RedisSpider): rdb = RedisDB() r = redis.Redis(host="127.0.0.1") name = 'relationship' allowed_domains = ['api.bilibili.com'] redis_key = "bili_relation_list" redis_set = "bili_relation_set" def parse(self,
nse): ret_dict = json.loads(response.text) status_code = ret_dict.get('code') if not status_code: if 'data' in ret_dict.keys(): info_dict = ret_dict.get('data') total = info_dict.get('total') focus_list = info_dict.get('list') user_id = response.url.strip('https://api.bilibili.com/x/relation/followings?vmid=').split('&')[0] for focus_item in focus_list: focus_info = Relationship() focus_info['total'] = total focus_info['user_id'] = user_id focus_info['focus_id'] = focus_item.get('mid') focus_info['focus_name'] = focus_item.get('uname') focus_info['focus_face'] = focus_item.get('face') focus_info['introduction'] = focus_item.get('sign') # 将 follower id 写入到待抓取队列 self.r.sadd(self.redis_set, focus_info.get('focus_id')) yield focus_info
respo
base_producer.rs
//! Low level Kafka producers. //! //! For more information about the producers provided in rdkafka, refer to the module level documentation. //! //! ## `BaseProducer` //! //! The `BaseProducer` is a low level Kafka producer designed to be as similar as possible to //! the underlying C librdkafka producer, while maintaining a safe Rust interface. //! //! Production of messages is fully asynchronous. The librdkafka producer will take care of buffering //! requests together according to configuration, and to send them efficiently. Once a message has //! been produced, or the retry count reached, a callback function called delivery callback will be //! called. //! //! The `BaseProducer` requires a `ProducerContext` which will be used to specify the delivery callback //! and the `DeliveryOpaque`. The `DeliveryOpaque` is a user-defined type that the user can pass to the //! `send` method of the producer, and that the producer will then forward to the delivery //! callback of the corresponding message. The `DeliveryOpaque` is useful in case the delivery //! callback requires additional information about the message (such as message id for example). //! //! ### Calling poll //! //! To execute delivery callbacks the `poll` method of the producer should be called regularly. //! If `poll` is not called, or not often enough, a `RDKafkaError::QueueFull` error will be returned. //! //! ## `ThreadedProducer` //! The `ThreadedProducer` is a wrapper around the `BaseProducer` which spawns a thread //! dedicated to calling `poll` on the producer at regular intervals, so that the user doesn't //! have to. The thread is started when the producer is created, and it will be terminated //! once the producer goes out of scope. //! //! A `RDKafkaError::QueueFull` error can still be returned in case the polling thread is not //! fast enough or Kafka is not able to receive data and acknowledge messages quickly enough. //! If this error is returned, the producer should wait and try again. //! use std::ffi::CString; use std::mem; use std::os::raw::c_void; use std::ptr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, RwLock}; use std::thread::{self, JoinHandle}; use std::time::Duration; use log::{trace, warn}; use rdkafka_sys as rdsys; use rdkafka_sys::rd_kafka_vtype_t::*; use rdkafka_sys::types::*; use crate::client::{Client, ClientContext}; use crate::config::{ClientConfig, FromClientConfig, FromClientConfigAndContext}; use crate::error::{IsError, KafkaError, KafkaResult}; use crate::message::{BorrowedMessage, OwnedHeaders, ToBytes}; use crate::util::{IntoOpaque, Timeout}; pub use crate::message::DeliveryResult; // // ********** PRODUCER CONTEXT ********** // /// A `ProducerContext` is an object that can be used during the creation of a producer to /// customizer its behavior. In particular, it can be used to specify the `delivery` callback /// that will be called when the ack from a delivered message is received. pub trait ProducerContext: ClientContext { /// A `DeliveryOpaque` is a user-defined structure that will be passed to the producer when /// producing a message, and returned to the `delivery` method once the message has been /// delivered, or failed to. type DeliveryOpaque: IntoOpaque; /// This method will be called once the message has been delivered (or failed to). The /// `DeliveryOpaque` will be the one provided by the user when calling send. fn delivery(&self, delivery_result: &DeliveryResult, delivery_opaque: Self::DeliveryOpaque); } /// Default producer context that can be use when a custom context is not required. #[derive(Clone)] pub struct DefaultProducerContext; impl ClientContext for DefaultProducerContext {} impl ProducerContext for DefaultProducerContext { type DeliveryOpaque = (); fn delivery(&self, _: &DeliveryResult, _: Self::DeliveryOpaque) {} } /// Callback that gets called from librdkafka every time a message succeeds or fails to be /// delivered. unsafe extern "C" fn delivery_cb<C: ProducerContext>( _client: *mut RDKafka, msg: *const RDKafkaMessage, _opaque: *mut c_void, ) { let producer_context = Box::from_raw(_opaque as *mut C); let delivery_opaque = C::DeliveryOpaque::from_ptr((*msg)._private); let owner = 42u8; // Wrap the message pointer into a BorrowedMessage that will only live for the body of this // function. let delivery_result = BorrowedMessage::from_dr_callback(msg as *mut RDKafkaMessage, &owner); trace!("Delivery event received: {:?}", delivery_result); (*producer_context).delivery(&delivery_result, delivery_opaque); mem::forget(producer_context); // Do not free the producer context match delivery_result { // Do not free the message, librdkafka will do it for us Ok(message) | Err((_, message)) => mem::forget(message), } } // // ********** BASE PRODUCER ********** // /// Producer record for the base producer /// /// The `BaseRecord` is a structure that can be used to provide a new record to /// [BaseProducer::send]. Since most fields are optional, a `BaseRecord` can be constructed /// using the builder pattern. /// /// # Examples /// /// This example will create a `BaseRecord` with no [DeliveryOpaque](ProducerContext::DeliveryOpaque): /// /// ```rust,no_run /// # use rdkafka::producer::BaseRecord; /// # use rdkafka::message::ToBytes; /// let record = BaseRecord::to("topic_name") // destination topic /// .key(&[1, 2, 3, 4]) // message key /// .payload("content") // message payload /// .partition(5); // target partition /// ``` /// /// The following example will build a similar record, but it will use a number as `DeliveryOpaque` /// for the message: /// /// ```rust,no_run /// # use rdkafka::producer::BaseRecord; /// # use rdkafka::message::ToBytes; /// let record = BaseRecord::with_opaque_to("topic_name", 123) // destination topic and message id /// .key(&[1, 2, 3, 4]) // message key /// .payload("content") // message payload /// .partition(5); // target partition /// ``` #[derive(Debug)] pub struct BaseRecord< 'a, K: ToBytes + ?Sized + 'a = (), P: ToBytes + ?Sized + 'a = (), D: IntoOpaque = (), > { /// Required destination topic pub topic: &'a str, /// Optional destination partition pub partition: Option<i32>, /// Optional payload pub payload: Option<&'a P>, /// Optional key pub key: Option<&'a K>, /// Optional timestamp pub timestamp: Option<i64>, /// Optional message headers pub headers: Option<OwnedHeaders>, /// Required delivery opaque (defaults to `()` if not required) pub delivery_opaque: D, } impl<'a, K: ToBytes + ?Sized, P: ToBytes + ?Sized, D: IntoOpaque> BaseRecord<'a, K, P, D> { /// Create a new record with the specified topic name and delivery opaque. pub fn with_opaque_to(topic: &'a str, delivery_opaque: D) -> BaseRecord<'a, K, P, D> { BaseRecord { topic, partition: None, payload: None, key: None, timestamp: None, headers: None, delivery_opaque, } } /// Set the destination partition of the record. pub fn partition(mut self, partition: i32) -> BaseRecord<'a, K, P, D> { self.partition = Some(partition); self } /// Set the payload of the record. pub fn payload(mut self, payload: &'a P) -> BaseRecord<'a, K, P, D> { self.payload = Some(payload); self } /// Set the key of the record. pub fn key(mut self, key: &'a K) -> BaseRecord<'a, K, P, D> { self.key = Some(key); self } /// Set the timestamp of the record. pub fn timestamp(mut self, timestamp: i64) -> BaseRecord<'a, K, P, D> { self.timestamp = Some(timestamp); self } /// Set the headers of the record. pub fn headers(mut self, headers: OwnedHeaders) -> BaseRecord<'a, K, P, D> { self.headers = Some(headers); self } } impl<'a, K: ToBytes + ?Sized, P: ToBytes + ?Sized> BaseRecord<'a, K, P, ()> { /// Create a new record with the specified topic name. pub fn to(topic: &'a str) -> BaseRecord<'a, K, P, ()> { BaseRecord { topic, partition: None, payload: None, key: None, timestamp: None, headers: None, delivery_opaque: (), } } } impl FromClientConfig for BaseProducer<DefaultProducerContext> { /// Creates a new `BaseProducer` starting from a configuration. fn from_config(config: &ClientConfig) -> KafkaResult<BaseProducer<DefaultProducerContext>> { BaseProducer::from_config_and_context(config, DefaultProducerContext) } } impl<C: ProducerContext> FromClientConfigAndContext<C> for BaseProducer<C> { /// Creates a new `BaseProducer` starting from a configuration and a context. fn from_config_and_context(config: &ClientConfig, context: C) -> KafkaResult<BaseProducer<C>> { let native_config = config.create_native_config()?; unsafe { rdsys::rd_kafka_conf_set_dr_msg_cb(native_config.ptr(), Some(delivery_cb::<C>)) }; let client = Client::new( config, native_config, RDKafkaType::RD_KAFKA_PRODUCER, context, )?; Ok(BaseProducer::from_client(client)) } } /// Low level Kafka producer. /// /// The `BaseProducer` needs to be polled at regular intervals in order to serve queued delivery /// report callbacks (for more information, refer to the module-level documentation). This producer /// can be cheaply cloned to create a new reference to the same underlying producer. /// /// # Example usage /// /// This code will send a message to Kafka. No custom [ProducerContext] is specified, so the /// [DefaultProducerContext] will be used. To see how to use a producer context, refer to the /// examples in the examples folder. /// ```rust /// use rdkafka::config::ClientConfig; /// use rdkafka::producer::{BaseProducer, BaseRecord}; /// use std::time::Duration; /// /// let producer: BaseProducer = ClientConfig::new() /// .set("bootstrap.servers", "kafka:9092") /// .create() /// .expect("Producer creation error"); /// /// producer.send( /// BaseRecord::to("destination_topic") /// .payload("this is the payload") /// .key("and this is a key"), /// ).expect("Failed to enqueue"); /// /// // Poll at regular intervals to process all the asynchronous delivery events. /// for _ in 0..10 { /// producer.poll(Duration::from_millis(100)); /// } /// /// // And/or flush the producer before dropping it. /// producer.flush(Duration::from_secs(1)); /// ``` pub struct BaseProducer<C: ProducerContext = DefaultProducerContext> { client_arc: Arc<Client<C>>, } impl<C: ProducerContext> BaseProducer<C> { /// Creates a base producer starting from a Client. fn from_client(client: Client<C>) -> BaseProducer<C> { BaseProducer { client_arc: Arc::new(client), } } /// Polls the producer. Regular calls to `poll` are required to process the events /// and execute the message delivery callbacks. Returns the number of events served. pub fn poll<T: Into<Timeout>>(&self, timeout: T) -> i32 { unsafe { rdsys::rd_kafka_poll(self.native_ptr(), timeout.into().as_millis()) } } /// Returns a pointer to the native Kafka client. fn native_ptr(&self) -> *mut RDKafka { self.client_arc.native_ptr() } /// Produce a message to Kafka. Message fields such as key, payload, partition, timestamp etc. /// are provided to this method via a [BaseRecord]. If the message is correctly enqueued in the /// producer's memory buffer, the method will take ownership of the record and return /// immediately; in case of failure to enqueue, the original record is returned, alongside an /// error code. If the message fails to be produced after being enqueued in the buffer, the /// [ProducerContext::delivery] method will be called asynchronously, with the provided /// [ProducerContext::DeliveryOpaque]. /// /// When no partition is specified the underlying Kafka library picks a partition based on a /// hash of the key. If no key is specified, a random partition will be used. To correctly /// handle errors, the delivery callback should be implemented. /// /// Note that this method will never block. // Simplifying the return type requires generic associated types, which are // unstable. #[allow(clippy::type_complexity)] pub fn send<'a, K, P>( &self, record: BaseRecord<'a, K, P, C::DeliveryOpaque>, ) -> Result<(), (KafkaError, BaseRecord<'a, K, P, C::DeliveryOpaque>)> where K: ToBytes + ?Sized, P: ToBytes + ?Sized,
/// Flushes the producer. Should be called before termination. This method will call `poll()` /// internally. pub fn flush<T: Into<Timeout>>(&self, timeout: T) { unsafe { rdsys::rd_kafka_flush(self.native_ptr(), timeout.into().as_millis()) }; } /// Returns the number of messages waiting to be sent, or sent but not acknowledged yet. pub fn in_flight_count(&self) -> i32 { unsafe { rdsys::rd_kafka_outq_len(self.native_ptr()) } } } impl<C: ProducerContext> Clone for BaseProducer<C> { fn clone(&self) -> BaseProducer<C> { BaseProducer { client_arc: self.client_arc.clone(), } } } // // ********** THREADED PRODUCER ********** // /// A producer with a separate thread for event handling. /// /// The `ThreadedProducer` is a `BaseProducer` with a separate thread dedicated to calling `poll` at /// regular intervals in order to execute any queued event, such as delivery notifications. The /// thread will be automatically stopped when the producer is dropped. #[must_use = "The threaded producer will stop immediately if unused"] pub struct ThreadedProducer<C: ProducerContext + 'static> { producer: BaseProducer<C>, should_stop: Arc<AtomicBool>, handle: RwLock<Option<JoinHandle<()>>>, } impl FromClientConfig for ThreadedProducer<DefaultProducerContext> { fn from_config(config: &ClientConfig) -> KafkaResult<ThreadedProducer<DefaultProducerContext>> { ThreadedProducer::from_config_and_context(config, DefaultProducerContext) } } impl<C: ProducerContext + 'static> FromClientConfigAndContext<C> for ThreadedProducer<C> { fn from_config_and_context( config: &ClientConfig, context: C, ) -> KafkaResult<ThreadedProducer<C>> { let threaded_producer = ThreadedProducer { producer: BaseProducer::from_config_and_context(config, context)?, should_stop: Arc::new(AtomicBool::new(false)), handle: RwLock::new(None), }; threaded_producer.start(); Ok(threaded_producer) } } impl<C: ProducerContext + 'static> ThreadedProducer<C> { /// Starts the polling thread that will drive the producer. The thread is already started by /// default. fn start(&self) { let producer_clone = self.producer.clone(); let should_stop = self.should_stop.clone(); let handle = thread::Builder::new() .name("producer polling thread".to_string()) .spawn(move || { trace!("Polling thread loop started"); loop { let n = producer_clone.poll(Duration::from_millis(100)); if n == 0 { if should_stop.load(Ordering::Relaxed) { // We received nothing and the thread should // stop, so break the loop. break; } } else { trace!("Received {} events", n); } } trace!("Polling thread loop terminated"); }) .expect("Failed to start polling thread"); let mut handle_store = self.handle.write().expect("poison error"); *handle_store = Some(handle); } /// Stops the polling thread. This method will be called during destruction. fn stop(&self) { let mut handle_store = self.handle.write().expect("poison error"); if (*handle_store).is_some() { trace!("Stopping polling"); self.should_stop.store(true, Ordering::Relaxed); trace!("Waiting for polling thread termination"); match (*handle_store).take().unwrap().join() { Ok(()) => trace!("Polling stopped"), Err(e) => warn!("Failure while terminating thread: {:?}", e), }; } } /// Sends a message to Kafka. See the documentation in `BaseProducer`. // Simplifying the return type requires generic associated types, which are // unstable. #[allow(clippy::type_complexity)] pub fn send<'a, K, P>( &self, record: BaseRecord<'a, K, P, C::DeliveryOpaque>, ) -> Result<(), (KafkaError, BaseRecord<'a, K, P, C::DeliveryOpaque>)> where K: ToBytes + ?Sized, P: ToBytes + ?Sized, { self.producer.send(record) } /// Polls the internal producer. This is not normally required since the `ThreadedProducer` had /// a thread dedicated to calling `poll` regularly. pub fn poll<T: Into<Timeout>>(&self, timeout: T) { self.producer.poll(timeout); } /// Flushes the producer. Should be called before termination. pub fn flush<T: Into<Timeout>>(&self, timeout: T) { self.producer.flush(timeout); } /// Returns the number of messages waiting to be sent, or send but not acknowledged yet. pub fn in_flight_count(&self) -> i32 { self.producer.in_flight_count() } } impl<C: ProducerContext + 'static> Drop for ThreadedProducer<C> { fn drop(&mut self) { trace!("Destroy ThreadedProducer"); self.stop(); trace!("ThreadedProducer destroyed"); } } #[cfg(test)] mod tests { // Just test that there are no panics, and that each struct implements the expected // traits (Clone, Send, Sync etc.). Behavior is tested in the integrations tests. use super::*; use crate::config::ClientConfig; // Verify that the producer is clone, according to documentation. #[test] fn test_base_producer_clone() { let producer = ClientConfig::new().create::<BaseProducer<_>>().unwrap(); let _producer_clone = producer.clone(); } }
{ let (payload_ptr, payload_len) = match record.payload.map(P::to_bytes) { None => (ptr::null_mut(), 0), Some(p) => (p.as_ptr() as *mut c_void, p.len()), }; let (key_ptr, key_len) = match record.key.map(K::to_bytes) { None => (ptr::null_mut(), 0), Some(k) => (k.as_ptr() as *mut c_void, k.len()), }; let topic_cstring = CString::new(record.topic.to_owned()).unwrap(); let produce_error = unsafe { rdsys::rd_kafka_producev( self.native_ptr(), RD_KAFKA_VTYPE_TOPIC, topic_cstring.as_ptr(), RD_KAFKA_VTYPE_PARTITION, record.partition.unwrap_or(-1), RD_KAFKA_VTYPE_MSGFLAGS, rdsys::RD_KAFKA_MSG_F_COPY as i32, RD_KAFKA_VTYPE_VALUE, payload_ptr, payload_len, RD_KAFKA_VTYPE_KEY, key_ptr, key_len, RD_KAFKA_VTYPE_OPAQUE, record.delivery_opaque.as_ptr(), RD_KAFKA_VTYPE_TIMESTAMP, record.timestamp.unwrap_or(0), RD_KAFKA_VTYPE_HEADERS, record .headers .as_ref() .map_or(ptr::null_mut(), OwnedHeaders::ptr), RD_KAFKA_VTYPE_END, ) }; if produce_error.is_error() { Err((KafkaError::MessageProduction(produce_error.into()), record)) } else { // The kafka producer now owns the delivery opaque and the headers mem::forget(record.delivery_opaque); mem::forget(record.headers); Ok(()) } }
manticore_protocol_challenge_Challenge__req_to_wire.rs
// Copyright lowRISC contributors.
// !! DO NOT EDIT !! // To regenerate this file, run `fuzz/generate_proto_tests.py`. #![no_main] #![allow(non_snake_case)] use libfuzzer_sys::fuzz_target; use manticore::protocol::Command; use manticore::protocol::wire::ToWire; use manticore::protocol::FuzzSafe; use manticore::protocol::challenge::Challenge as C; type Req<'a> = <C as Command<'a>>::Req; fuzz_target!(|data: <Req<'static> as FuzzSafe>::Safe| { let mut out = [0u8; 1024]; let _ = Req::from_safe(&data).to_wire(&mut &mut out[..]); });
// Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0
trellisboard.py
#!/usr/bin/env python3 # # This file is part of LiteX-Boards. # # Copyright (c) 2019 David Shah <[email protected]> # SPDX-License-Identifier: BSD-2-Clause import os import argparse from migen import * from migen.genlib.resetsync import AsyncResetSynchronizer from litex_boards.platforms import trellisboard from litex.build.lattice.trellis import trellis_args, trellis_argdict from litex.soc.cores.clock import * from litex.soc.integration.soc_core import * from litex.soc.integration.builder import * from litex.soc.cores.led import LedChaser from litex.soc.cores.gpio import GPIOTristate from litedram.modules import MT41J256M16 from litedram.phy import ECP5DDRPHY from liteeth.phy.ecp5rgmii import LiteEthPHYRGMII # CRG ---------------------------------------------------------------------------------------------- class _CRG(Module): def
(self, platform, sys_clk_freq): self.rst = Signal() self.clock_domains.cd_por = ClockDomain(reset_less=True) self.clock_domains.cd_sys = ClockDomain() # # # # Clk / Rst clk12 = platform.request("clk12") rst = platform.request("user_btn", 0) # Power on reset por_count = Signal(16, reset=2**16-1) por_done = Signal() self.comb += self.cd_por.clk.eq(clk12) self.comb += por_done.eq(por_count == 0) self.sync.por += If(~por_done, por_count.eq(por_count - 1)) # PLL self.submodules.pll = pll = ECP5PLL() self.comb += pll.reset.eq(~por_done | rst | self.rst) pll.register_clkin(clk12, 12e6) pll.create_clkout(self.cd_sys, sys_clk_freq) class _CRGSDRAM(Module): def __init__(self, platform, sys_clk_freq): self.rst = Signal() self.clock_domains.cd_init = ClockDomain() self.clock_domains.cd_por = ClockDomain(reset_less=True) self.clock_domains.cd_sys = ClockDomain() self.clock_domains.cd_sys2x = ClockDomain() self.clock_domains.cd_sys2x_i = ClockDomain(reset_less=True) # # # self.stop = Signal() self.reset = Signal() # Clk / Rst clk12 = platform.request("clk12") rst = platform.request("user_btn", 0) # Power on reset por_count = Signal(16, reset=2**16-1) por_done = Signal() self.comb += self.cd_por.clk.eq(clk12) self.comb += por_done.eq(por_count == 0) self.sync.por += If(~por_done, por_count.eq(por_count - 1)) # PLL sys2x_clk_ecsout = Signal() self.submodules.pll = pll = ECP5PLL() self.comb += pll.reset.eq(~por_done | rst | self.rst) pll.register_clkin(clk12, 12e6) pll.create_clkout(self.cd_sys2x_i, 2*sys_clk_freq) pll.create_clkout(self.cd_init, 25e6) self.specials += [ Instance("ECLKBRIDGECS", i_CLK0 = self.cd_sys2x_i.clk, i_SEL = 0, o_ECSOUT = sys2x_clk_ecsout, ), Instance("ECLKSYNCB", i_ECLKI = sys2x_clk_ecsout, i_STOP = self.stop, o_ECLKO = self.cd_sys2x.clk), Instance("CLKDIVF", p_DIV = "2.0", i_ALIGNWD = 0, i_CLKI = self.cd_sys2x.clk, i_RST = self.reset, o_CDIVX = self.cd_sys.clk), AsyncResetSynchronizer(self.cd_sys, ~pll.locked | self.reset), AsyncResetSynchronizer(self.cd_sys2x, ~pll.locked | self.reset), ] self.comb += platform.request("dram_vtt_en").eq(1) # BaseSoC ------------------------------------------------------------------------------------------ class BaseSoC(SoCCore): def __init__(self, sys_clk_freq=int(75e6), toolchain="trellis", with_ethernet=False, with_led_chaser=True, with_pmod_gpio=False, **kwargs): platform = trellisboard.Platform(toolchain=toolchain) # SoCCore ---------------------------------------------------------------------------------- SoCCore.__init__(self, platform, sys_clk_freq, ident = "LiteX SoC on Trellis Board", ident_version = True, **kwargs) # CRG -------------------------------------------------------------------------------------- crg_cls = _CRGSDRAM if not self.integrated_main_ram_size else _CRG self.submodules.crg = crg_cls(platform, sys_clk_freq) # DDR3 SDRAM ------------------------------------------------------------------------------- if not self.integrated_main_ram_size: self.submodules.ddrphy = ECP5DDRPHY( platform.request("ddram"), sys_clk_freq=sys_clk_freq) self.comb += self.crg.stop.eq(self.ddrphy.init.stop) self.comb += self.crg.reset.eq(self.ddrphy.init.reset) self.add_sdram("sdram", phy = self.ddrphy, module = MT41J256M16(sys_clk_freq, "1:2"), l2_cache_size = kwargs.get("l2_size", 8192), ) # Ethernet --------------------------------------------------------------------------------- if with_ethernet: self.submodules.ethphy = LiteEthPHYRGMII( clock_pads = self.platform.request("eth_clocks"), pads = self.platform.request("eth")) self.add_ethernet(phy=self.ethphy) # Leds ------------------------------------------------------------------------------------- if with_led_chaser: self.submodules.leds = LedChaser( pads = platform.request_all("user_led"), sys_clk_freq = sys_clk_freq) # GPIOs ------------------------------------------------------------------------------------ if with_pmod_gpio: platform.add_extension(trellisboard.raw_pmod_io("pmoda")) self.submodules.gpio = GPIOTristate(platform.request("pmoda")) # Build -------------------------------------------------------------------------------------------- def main(): parser = argparse.ArgumentParser(description="LiteX SoC on Trellis Board") parser.add_argument("--build", action="store_true", help="Build bitstream") parser.add_argument("--load", action="store_true", help="Load bitstream") parser.add_argument("--toolchain", default="trellis", help="FPGA toolchain: trellis (default) or diamond") parser.add_argument("--sys-clk-freq", default=75e6, help="System clock frequency (default: 75MHz)") parser.add_argument("--with-ethernet", action="store_true", help="Enable Ethernet support") sdopts = parser.add_mutually_exclusive_group() sdopts.add_argument("--with-spi-sdcard", action="store_true", help="Enable SPI-mode SDCard support") sdopts.add_argument("--with-sdcard", action="store_true", help="Enable SDCard support") parser.add_argument("--with-pmod-gpio", action="store_true", help="Enable GPIOs through PMOD") # FIXME: Temporary test. builder_args(parser) soc_core_args(parser) trellis_args(parser) args = parser.parse_args() soc = BaseSoC( sys_clk_freq = int(float(args.sys_clk_freq)), with_ethernet = args.with_ethernet, with_pmod_gpio = args.with_pmod_gpio, **soc_core_argdict(args) ) if args.with_spi_sdcard: soc.add_spi_sdcard() if args.with_sdcard: soc.add_sdcard() builder = Builder(soc, **builder_argdict(args)) builder_kargs = trellis_argdict(args) if args.toolchain == "trellis" else {} builder.build(**builder_kargs, run=args.build) if args.load: prog = soc.platform.create_programmer() prog.load_bitstream(os.path.join(builder.gateware_dir, soc.build_name + ".svf")) if __name__ == "__main__": main()
__init__
9adf959c.5a4538db.js
(window.webpackJsonp=window.webpackJsonp||[]).push([[282],{353:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return s})),n.d(t,"metadata",(function(){return c})),n.d(t,"toc",(function(){return o})),n.d(t,"default",(function(){return u}));var a=n(3),r=n(8),l=(n(0),n(568)),b=n(572),i=n(573),s={title:"REST API",id:"api"},c={unversionedId:"reference/api",id:"version-v1.10/reference/api",isDocsHomePage:!1,title:"REST API",description:"Welcome to the ORY Hydra HTTP API documentation. You will find documentation for",source:"@site/versioned_docs/version-v1.10/reference/api.mdx",slug:"/reference/api",permalink:"/hydra/docs/reference/api",editUrl:"https://github.com/ory/hydra/edit/master/docs/versioned_docs/version-v1.10/reference/api.mdx",version:"v1.10",sidebar:"version-v1.10/docs",previous:{title:"Configuration",permalink:"/hydra/docs/reference/configuration"},next:{title:"hydra",permalink:"/hydra/docs/cli/hydra"}},o=[{value:"Authentication",id:"authentication",children:[]},{value:"Public Endpoints",id:"public-endpoints",children:[{value:"JSON Web Keys Discovery",id:"json-web-keys-discovery",children:[]},{value:"OpenID Connect Discovery",id:"openid-connect-discovery",children:[]},{value:"Check Readiness Status",id:"check-readiness-status",children:[]},{value:"The OAuth 2.0 Authorize Endpoint",id:"the-oauth-20-authorize-endpoint",children:[]},{value:"Revoke OAuth2 Tokens",id:"revoke-oauth2-tokens",children:[]},{value:"OpenID Connect Front-Backchannel Enabled Logout",id:"openid-connect-front-backchannel-enabled-logout",children:[]},{value:"The OAuth 2.0 Token Endpoint",id:"the-oauth-20-token-endpoint",children:[]},{value:"OpenID Connect Userinfo",id:"openid-connect-userinfo",children:[]}]},{value:"Administrative Endpoints",id:"administrative-endpoints",children:[{value:"List OAuth 2.0 Clients",id:"list-oauth-20-clients",children:[]},{value:"Create an OAuth 2.0 Client",id:"create-an-oauth-20-client",children:[]},{value:"Get an OAuth 2.0 Client.",id:"get-an-oauth-20-client",children:[]},{value:"Update an OAuth 2.0 Client",id:"update-an-oauth-20-client",children:[]},{value:"Deletes an OAuth 2.0 Client",id:"deletes-an-oauth-20-client",children:[]},{value:"Check Alive Status",id:"check-alive-status",children:[]},{value:"Retrieve a JSON Web Key Set",id:"retrieve-a-json-web-key-set",children:[]},{value:"Update a JSON Web Key Set",id:"update-a-json-web-key-set",children:[]},{value:"Generate a New JSON Web Key",id:"generate-a-new-json-web-key",children:[]},{value:"Delete a JSON Web Key Set",id:"delete-a-json-web-key-set",children:[]},{value:"Fetch a JSON Web Key",id:"fetch-a-json-web-key",children:[]},{value:"Update a JSON Web Key",id:"update-a-json-web-key",children:[]},{value:"Delete a JSON Web Key",id:"delete-a-json-web-key",children:[]},{value:"Get Snapshot Metrics from the Hydra Service.",id:"get-snapshot-metrics-from-the-hydra-service",children:[]},{value:"Get Consent Request Information",id:"get-consent-request-information",children:[]},{value:"Accept a Consent Request",id:"accept-a-consent-request",children:[]},{value:"Reject a Consent Request",id:"reject-a-consent-request",children:[]},{value:"Get a Login Request",id:"get-a-login-request",children:[]},{value:"Accept a Login Request",id:"accept-a-login-request",children:[]},{value:"Reject a Login Request",id:"reject-a-login-request",children:[]},{value:"Get a Logout Request",id:"get-a-logout-request",children:[]},{value:"Accept a Logout Request",id:"accept-a-logout-request",children:[]},{value:"Reject a Logout Request",id:"reject-a-logout-request",children:[]},{value:"Lists All Consent Sessions of a Subject",id:"lists-all-consent-sessions-of-a-subject",children:[]},{value:"Revokes Consent Sessions of a Subject for a Specific OAuth 2.0 Client",id:"revokes-consent-sessions-of-a-subject-for-a-specific-oauth-20-client",children:[]},{value:"Invalidates All Login Sessions of a Certain User",id:"invalidates-all-login-sessions-of-a-certain-user",children:[]},{value:"Flush Expired OAuth2 Access Tokens",id:"flush-expired-oauth2-access-tokens",children:[]},{value:"Introspect OAuth2 Tokens",id:"introspect-oauth2-tokens",children:[]},{value:"Delete OAuth2 Access Tokens from a Client",id:"delete-oauth2-access-tokens-from-a-client",children:[]},{value:"Get Service Version",id:"get-service-version",children:[]}]},{value:"Schemas",id:"schemas",children:[]}],p={toc:o};function u(e){var t=e.components,n=Object(r.a)(e,["components"]);return Object(l.b)("wrapper",Object(a.a)({},p,n,{components:t,mdxType:"MDXLayout"}),Object(l.b)("p",null,"Welcome to the ORY Hydra HTTP API documentation. You will find documentation for\nall HTTP APIs here."),Object(l.b)("div",{className:"admonition admonition-info alert alert--info"},Object(l.b)("div",{parentName:"div",className:"admonition-heading"},Object(l.b)("h5",{parentName:"div"},Object(l.b)("span",{parentName:"h5",className:"admonition-icon"},Object(l.b)("svg",{parentName:"span",xmlns:"http://www.w3.org/2000/svg",width:"14",height:"16",viewBox:"0 0 14 16"},Object(l.b)("path",{parentName:"svg",fillRule:"evenodd",d:"M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"}))),"info")),Object(l.b)("div",{parentName:"div",className:"admonition-content"},Object(l.b)("p",{parentName:"div"},"You are viewing REST API documentation. This documentation is auto-generated\nfrom a swagger specification which itself is generated from annotations in the\nsource code of the project. It is possible that this documentation includes bugs\nand that code samples are incomplete or wrong."),Object(l.b)("p",{parentName:"div"},"If you find issues in the respective documentation, please do not edit the\nMarkdown files directly (as they are generated) but raise an issue on the\nproject's GitHub presence instead. This documentation will improve over time\nwith your help! If you have ideas how to improve this part of the documentation,\nfeel free to share them in a\n",Object(l.b)("a",{parentName:"p",href:"https://github.com/ory/docs/issues/new"},"GitHub issue")," any time."))),Object(l.b)("h2",{id:"authentication"},"Authentication"),Object(l.b)("ul",null,Object(l.b)("li",{parentName:"ul"},Object(l.b)("p",{parentName:"li"},"HTTP Authentication, scheme: basic - OAuth 2.0 Authorization. - Flow:\nauthorizationCode"),Object(l.b)("ul",{parentName:"li"},Object(l.b)("li",{parentName:"ul"},Object(l.b)("p",{parentName:"li"},"OAuth 2.0 Authorization URL =\n",Object(l.b)("a",{parentName:"p",href:"https://hydra.demo.ory.sh/oauth2/auth"},"https://hydra.demo.ory.sh/oauth2/auth"))),Object(l.b)("li",{parentName:"ul"},Object(l.b)("p",{parentName:"li"},"OAuth 2.0 Token URL =\n",Object(l.b)("a",{parentName:"p",href:"https://hydra.demo.ory.sh/oauth2/token"},"https://hydra.demo.ory.sh/oauth2/token"))),Object(l.b)("li",{parentName:"ul"},Object(l.b)("p",{parentName:"li"},"OAuth 2.0 Scope"),Object(l.b)("table",{parentName:"li"},Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Scope"),Object(l.b)("th",{parentName:"tr",align:null},"Scope Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"offline"),Object(l.b)("td",{parentName:"tr",align:null},"A scope required when requesting refresh tokens (alias for ",Object(l.b)("inlineCode",{parentName:"td"},"offline_access"),")")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"offline_access"),Object(l.b)("td",{parentName:"tr",align:null},"A scope required when requesting refresh tokens")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"openid"),Object(l.b)("td",{parentName:"tr",align:null},"Request an OpenID Connect ID Token")))))))),Object(l.b)("a",{id:"ory-hydra-public-endpoints"}),Object(l.b)("h2",{id:"public-endpoints"},"Public Endpoints"),Object(l.b)("a",{id:"opIdwellKnown"}),Object(l.b)("h3",{id:"json-web-keys-discovery"},"JSON Web Keys Discovery"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /.well-known/jwks.json HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint returns JSON Web Keys to be used as public keys for verifying\nOpenID Connect ID Tokens and, if enabled, OAuth 2.0 JWT Access Tokens. This\nendpoint can be used with client libraries like\n",Object(l.b)("a",{parentName:"p",href:"https://github.com/auth0/node-jwks-rsa"},"node-jwks-rsa")," among others."),Object(l.b)("h4",{id:"responses"},"Responses"),Object(l.b)("a",{id:"json-web-keys-discovery-responses"}),Object(l.b)("h5",{id:"overview"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"JSONWebKeySet"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkeyset"},"JSONWebKeySet"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples"},"Examples"),Object(l.b)("h6",{id:"200-response"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "keys": [\n {\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n }\n ]\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /.well-known/jwks.json \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/.well-known/jwks.json", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/.well-known/jwks.json', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/.well-known/jwks.json");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/.well-known/jwks.json',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/.well-known/jwks.json',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIddiscoverOpenIDConfiguration"}),Object(l.b)("h3",{id:"openid-connect-discovery"},"OpenID Connect Discovery"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /.well-known/openid-configuration HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"The well known endpoint an be used to retrieve information for OpenID Connect\nclients. We encourage you to not roll your own OpenID Connect client but to use\nan OpenID Connect client library instead. You can learn more on this flow at\n",Object(l.b)("a",{parentName:"p",href:"https://openid.net/specs/openid-connect-discovery-1_0.html"},"https://openid.net/specs/openid-connect-discovery-1_0.html")," ."),Object(l.b)("p",null,"Popular libraries for OpenID Connect clients include oidc-client-js\n(JavaScript), go-oidc (Golang), and others. For a full list of clients go here:\n",Object(l.b)("a",{parentName:"p",href:"https://openid.net/developers/certified/"},"https://openid.net/developers/certified/")),Object(l.b)("h4",{id:"responses-1"},"Responses"),Object(l.b)("a",{id:"openid-connect-discovery-responses"}),Object(l.b)("h5",{id:"overview-1"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"wellKnown"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemawellknown"},"wellKnown"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-1"},"Examples"),Object(l.b)("h6",{id:"200-response-1"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "authorization_endpoint": "https://playground.ory.sh/ory-hydra/public/oauth2/auth",\n "backchannel_logout_session_supported": true,\n "backchannel_logout_supported": true,\n "claims_parameter_supported": true,\n "claims_supported": ["string"],\n "end_session_endpoint": "string",\n "frontchannel_logout_session_supported": true,\n "frontchannel_logout_supported": true,\n "grant_types_supported": ["string"],\n "id_token_signing_alg_values_supported": ["string"],\n "issuer": "https://playground.ory.sh/ory-hydra/public/",\n "jwks_uri": "https://playground.ory.sh/ory-hydra/public/.well-known/jwks.json",\n "registration_endpoint": "https://playground.ory.sh/ory-hydra/admin/client",\n "request_object_signing_alg_values_supported": ["string"],\n "request_parameter_supported": true,\n "request_uri_parameter_supported": true,\n "require_request_uri_registration": true,\n "response_modes_supported": ["string"],\n "response_types_supported": ["string"],\n "revocation_endpoint": "string",\n "scopes_supported": ["string"],\n "subject_types_supported": ["string"],\n "token_endpoint": "https://playground.ory.sh/ory-hydra/public/oauth2/token",\n "token_endpoint_auth_methods_supported": ["string"],\n "userinfo_endpoint": "string",\n "userinfo_signing_alg_values_supported": ["string"]\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-1"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /.well-known/openid-configuration \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/.well-known/openid-configuration", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/.well-known/openid-configuration', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/.well-known/openid-configuration");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/.well-known/openid-configuration',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/.well-known/openid-configuration',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdisInstanceReady"}),Object(l.b)("h3",{id:"check-readiness-status"},"Check Readiness Status"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /health/ready HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint returns a 200 status code when the HTTP server is up running and\nthe environment dependencies (e.g. the database) are responsive as well."),Object(l.b)("p",null,"If the service supports TLS Edge Termination, this endpoint does not require the\n",Object(l.b)("inlineCode",{parentName:"p"},"X-Forwarded-Proto")," header to be set."),Object(l.b)("p",null,"Be aware that if you are running multiple nodes of this service, the health\nstatus will never refer to the cluster state, only to a single instance."),Object(l.b)("h4",{id:"responses-2"},"Responses"),Object(l.b)("a",{id:"check-readiness-status-responses"}),Object(l.b)("h5",{id:"overview-2"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"healthStatus"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemahealthstatus"},"healthStatus"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"503"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.4"},"Service Unavailable")),Object(l.b)("td",{parentName:"tr",align:null},"healthNotReadyStatus"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemahealthnotreadystatus"},"healthNotReadyStatus"))))),Object(l.b)("h5",{id:"examples-2"},"Examples"),Object(l.b)("h6",{id:"200-response-2"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "status": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-2"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /health/ready \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/health/ready", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/health/ready', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/health/ready");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/health/ready',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/health/ready',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdoauthAuth"}),Object(l.b)("h3",{id:"the-oauth-20-authorize-endpoint"},"The OAuth 2.0 Authorize Endpoint"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /oauth2/auth HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint is not documented here because you should never use your own\nimplementation to perform OAuth2 flows. OAuth2 is a very popular protocol and a\nlibrary for your programming language will exists."),Object(l.b)("p",null,"To learn more about this flow please refer to the specification:\n",Object(l.b)("a",{parentName:"p",href:"https://tools.ietf.org/html/rfc6749"},"https://tools.ietf.org/html/rfc6749")),Object(l.b)("h4",{id:"responses-3"},"Responses"),Object(l.b)("a",{id:"the-oauth-2.0-authorize-endpoint-responses"}),Object(l.b)("h5",{id:"overview-3"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"302"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.4.3"},"Found")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-3"},"Examples"),Object(l.b)("h6",{id:"401-response"},"401 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-3"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /oauth2/auth \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/oauth2/auth", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/oauth2/auth', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/oauth2/auth',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/oauth2/auth',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdrevokeOAuth2Token"}),Object(l.b)("h3",{id:"revoke-oauth2-tokens"},"Revoke OAuth2 Tokens"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"POST /oauth2/revoke HTTP/1.1\nContent-Type: application/x-www-form-urlencoded\nAccept: application/json\n\n")),Object(l.b)("p",null,"Revoking a token (both access and refresh) means that the tokens will be\ninvalid. A revoked access token can no longer be used to make access requests,\nand a revoked refresh token can no longer be used to refresh an access token.\nRevoking a refresh token also invalidates the access token that was created with\nit. A token may only be revoked by the client the token was generated for."),Object(l.b)("h4",{id:"request-body"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-yaml"},"token: string\n")),Object(l.b)("a",{id:"revoke-oauth2-tokens-parameters"}),Object(l.b)("h4",{id:"parameters"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb token"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-4"},"Responses"),Object(l.b)("a",{id:"revoke-oauth2-tokens-responses"}),Object(l.b)("h5",{id:"overview-4"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-4"},"Examples"),Object(l.b)("h6",{id:"401-response-1"},"401 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"warning"},"To perform this operation, you must be authenticated by means of one of the following methods: basic, oauth2"),Object(l.b)("h4",{id:"code-samples-4"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X POST /oauth2/revoke \\\n -H 'Content-Type: application/x-www-form-urlencoded' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/x-www-form-urlencoded"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("POST", "/oauth2/revoke", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch');\nconst input = '{\n \"token\": \"string\"\n}';\nconst headers = {\n 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'\n}\n\nfetch('/oauth2/revoke', {\n method: 'POST',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/revoke");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("POST");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'application/json'\n}\n\nr = requests.post(\n '/oauth2/revoke',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.post '/oauth2/revoke',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIddisconnectUser"}),Object(l.b)("h3",{id:"openid-connect-front-backchannel-enabled-logout"},"OpenID Connect Front-Backchannel Enabled Logout"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /oauth2/sessions/logout HTTP/1.1\n\n")),Object(l.b)("p",null,"This endpoint initiates and completes user logout at ORY Hydra and initiates\nOpenID Connect Front-/Back-channel logout:"),Object(l.b)("p",null,Object(l.b)("a",{parentName:"p",href:"https://openid.net/specs/openid-connect-frontchannel-1_0.html"},"https://openid.net/specs/openid-connect-frontchannel-1_0.html"),"\n",Object(l.b)("a",{parentName:"p",href:"https://openid.net/specs/openid-connect-backchannel-1_0.html"},"https://openid.net/specs/openid-connect-backchannel-1_0.html")),Object(l.b)("h4",{id:"responses-5"},"Responses"),Object(l.b)("a",{id:"openid-connect-front-backchannel-enabled-logout-responses"}),Object(l.b)("h5",{id:"overview-5"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"302"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.4.3"},"Found")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")))),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-5"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /oauth2/sessions/logout\n\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/oauth2/sessions/logout", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nfetch('/oauth2/sessions/logout', {\n method: 'GET'\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/sessions/logout");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nr = requests.get(\n '/oauth2/sessions/logout',\n params={)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nresult = RestClient.get '/oauth2/sessions/logout',\n params: {}\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdoauth2Token"}),Object(l.b)("h3",{id:"the-oauth-20-token-endpoint"},"The OAuth 2.0 Token Endpoint"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"POST /oauth2/token HTTP/1.1\nContent-Type: application/x-www-form-urlencoded\nAccept: application/json\n\n")),Object(l.b)("p",null,'The client makes a request to the token endpoint by sending the following\nparameters using the "application/x-www-form-urlencoded" HTTP request\nentity-body.'),Object(l.b)("blockquote",null,Object(l.b)("p",{parentName:"blockquote"},"Do not implement a client for this endpoint yourself. Use a library. There are\nmany libraries available for any programming language. You can find a list of\nlibraries here: ",Object(l.b)("a",{parentName:"p",href:"https://oauth.net/code/"},"https://oauth.net/code/")),Object(l.b)("p",{parentName:"blockquote"},"Do note that Hydra SDK does not implement this endpoint properly. Use one of\nthe libraries listed above!")),Object(l.b)("h4",{id:"request-body-1"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-yaml"},"grant_type: string\ncode: string\nrefresh_token: string\nredirect_uri: string\nclient_id: string\n")),Object(l.b)("a",{id:"the-oauth-2.0-token-endpoint-parameters"}),Object(l.b)("h4",{id:"parameters-1"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb grant_type"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb code"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb refresh_token"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb redirect_uri"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb client_id"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-6"},"Responses"),Object(l.b)("a",{id:"the-oauth-2.0-token-endpoint-responses"}),Object(l.b)("h5",{id:"overview-6"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"oauth2TokenResponse"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2tokenresponse"},"oauth2TokenResponse"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"400"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.1"},"Bad Request")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-5"},"Examples"),Object(l.b)("h6",{id:"200-response-3"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "access_token": "string",\n "expires_in": 0,\n "id_token": "string",\n "refresh_token": "string",\n "scope": "string",\n "token_type": "string"\n}\n')),Object(l.b)("aside",{class:"warning"},"To perform this operation, you must be authenticated by means of one of the following methods: basic, oauth2"),Object(l.b)("h4",{id:"code-samples-6"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X POST /oauth2/token \\\n -H 'Content-Type: application/x-www-form-urlencoded' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/x-www-form-urlencoded"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("POST", "/oauth2/token", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "grant_type": "string",\n "code": "string",\n "refresh_token": "string",\n "redirect_uri": "string",\n "client_id": "string"\n}\';\nconst headers = {\n \'Content-Type\': \'application/x-www-form-urlencoded\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/oauth2/token\', {\n method: \'POST\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/token");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("POST");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'application/json'\n}\n\nr = requests.post(\n '/oauth2/token',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.post '/oauth2/token',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIduserinfo"}),Object(l.b)("h3",{id:"openid-connect-userinfo"},"OpenID Connect Userinfo"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /userinfo HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint returns the payload of the ID Token, including the idTokenExtra\nvalues, of the provided OAuth 2.0 Access Token."),Object(l.b)("p",null,"For more information please\n",Object(l.b)("a",{parentName:"p",href:"http://openid.net/specs/openid-connect-core-1_0.html#UserInfo"},"refer to the spec"),"."),Object(l.b)("h4",{id:"responses-7"},"Responses"),Object(l.b)("a",{id:"openid-connect-userinfo-responses"}),Object(l.b)("h5",{id:"overview-7"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"userinfoResponse"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemauserinforesponse"},"userinfoResponse"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-6"},"Examples"),Object(l.b)("h6",{id:"200-response-4"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "birthdate": "string",\n "email": "string",\n "email_verified": true,\n "family_name": "string",\n "gender": "string",\n "given_name": "string",\n "locale": "string",\n "middle_name": "string",\n "name": "string",\n "nickname": "string",\n "phone_number": "string",\n "phone_number_verified": true,\n "picture": "string",\n "preferred_username": "string",\n "profile": "string",\n "sub": "string",\n "updated_at": 0,\n "website": "string",\n "zoneinfo": "string"\n}\n')),Object(l.b)("aside",{class:"warning"},"To perform this operation, you must be authenticated by means of one of the following methods: oauth2"),Object(l.b)("h4",{id:"code-samples-7"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /userinfo \\\n -H 'Accept: application/json' \\ -H 'Authorization: Bearer {access-token}'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n "Authorization": []string{"Bearer {access-token}"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/userinfo", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json',\n Authorization: 'Bearer {access-token}'\n}\n\nfetch('/userinfo', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/userinfo");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json',\n 'Authorization': 'Bearer {access-token}'\n}\n\nr = requests.get(\n '/userinfo',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json',\n 'Authorization' => 'Bearer {access-token}'\n}\n\nresult = RestClient.get '/userinfo',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"ory-hydra-administrative-endpoints"}),Object(l.b)("h2",{id:"administrative-endpoints"},"Administrative Endpoints"),Object(l.b)("a",{id:"opIdlistOAuth2Clients"}),Object(l.b)("h3",{id:"list-oauth-20-clients"},"List OAuth 2.0 Clients"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /clients HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint lists all clients in the database, and never returns client\nsecrets. As a default it lists the first 100 clients. The ",Object(l.b)("inlineCode",{parentName:"p"},"limit")," parameter can\nbe used to retrieve more clients, but it has an upper bound at 500 objects.\nPagination should be used to retrieve more than 500 objects."),Object(l.b)("p",null,'OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows.\nUsually, OAuth 2.0 clients are generated for applications which want to consume\nyour OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will\nneed an OAuth 2.0 Client as well. Make sure that this endpoint is well protected\nand only callable by first-party components. The "Link" header is also included\nin successful responses, which contains one or more links for pagination,\nformatted like so:\n\'',Object(l.b)("a",{parentName:"p",href:"https://hydra-url/admin/clients?limit=%7Blimit%7D&offset=%7Boffset%7D"},"https://hydra-url/admin/clients?limit={limit}&offset={offset}"),"; rel=\"{page}\"',\nwhere page is one of the following applicable pages: 'first', 'next', 'last',\nand 'previous'. Multiple links can be included in this header, and will be\nseparated by a comma."),Object(l.b)("a",{id:"list-oauth-2.0-clients-parameters"}),Object(l.b)("h4",{id:"parameters-2"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"limit"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"The maximum amount of policies returned, upper bound is 500 policies")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"offset"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"The offset from where to start looking.")))),Object(l.b)("h4",{id:"responses-8"},"Responses"),Object(l.b)("a",{id:"list-oauth-2.0-clients-responses"}),Object(l.b)("h5",{id:"overview-8"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"A list of clients."),Object(l.b)("td",{parentName:"tr",align:null},"Inline")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("a",{id:"list-oauth-2.0-clients-responseschema"}),Object(l.b)("h5",{id:"response-schema"},"Response Schema"),Object(l.b)("p",null,"Status Code ",Object(l.b)("strong",{parentName:"p"},"200")),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("em",{parentName:"td"},"anonymous")),Object(l.b)("td",{parentName:"tr",align:null},"[",Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client"),"]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb Client represents an OAuth 2.0 Client."),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb allowed_cors_origins"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb audience"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb backchannel_logout_session_required"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the RP requires that a sid (session ID) Claim be included in the Logout",Object(l.b)("br",null),"Token to identify the RP session with the OP when the backchannel_logout_uri is used.",Object(l.b)("br",null),"If omitted, the default value is false.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb backchannel_logout_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RP URL that will cause the RP to log itself out when sent a Logout Token by the OP.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb client_id"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ID is the id for this client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb client_name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Name is the human-readable string name of the client to be presented to the",Object(l.b)("br",null),"end-user during authorization.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb client_secret"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Secret is the client's secret. The secret will be included in the create request as cleartext, and then",Object(l.b)("br",null),"never again. The secret is stored using BCrypt so it is impossible to recover it. Tell your users",Object(l.b)("br",null),"that they need to write the secret down as it will not be made available again.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb client_secret_expires_at"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"SecretExpiresAt is an integer holding the time at which the client",Object(l.b)("br",null),"secret will expire or 0 if it will not expire. The time is",Object(l.b)("br",null),"represented as the number of seconds from 1970-01-01T00:00:00Z as",Object(l.b)("br",null),"measured in UTC until the date/time of expiration.",Object(l.b)("br",null),Object(l.b)("br",null),"This feature is currently not supported and it's value will always",Object(l.b)("br",null),"be set to 0.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb client_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ClientURI is an URL string of a web page providing information about the client.",Object(l.b)("br",null),"If present, the server SHOULD display this URL to the end-user in",Object(l.b)("br",null),"a clickable fashion.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb contacts"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb created_at"),Object(l.b)("td",{parentName:"tr",align:null},"string(date-time)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"CreatedAt returns the timestamp of the client's creation.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb frontchannel_logout_session_required"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the RP requires that iss (issuer) and sid (session ID) query parameters be",Object(l.b)("br",null),"included to identify the RP session with the OP when the frontchannel_logout_uri is used.",Object(l.b)("br",null),"If omitted, the default value is false.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb frontchannel_logout_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RP URL that will cause the RP to log itself out when rendered in an iframe by the OP. An iss (issuer) query",Object(l.b)("br",null),"parameter and a sid (session ID) query parameter MAY be included by the OP to enable the RP to validate the",Object(l.b)("br",null),"request and to determine which of the potentially multiple sessions is to be logged out; if either is",Object(l.b)("br",null),"included, both MUST be.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb grant_types"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb jwks"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajosejsonwebkeyset"},"JoseJSONWebKeySet")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb jwks_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL for the Client's JSON Web Key Set ","[JWK]"," document. If the Client signs requests to the Server, it contains",Object(l.b)("br",null),"the signing key(s) the Server uses to validate signatures from the Client. The JWK Set MAY also contain the",Object(l.b)("br",null),"Client's encryption keys(s), which are used by the Server to encrypt responses to the Client. When both signing",Object(l.b)("br",null),"and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all keys in the referenced",Object(l.b)("br",null),"JWK Set to indicate each key's intended usage. Although some algorithms allow the same key to be used for both",Object(l.b)("br",null),"signatures and encryption, doing so is NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used",Object(l.b)("br",null),"to provide X.509 representations of keys provided. When used, the bare key values MUST still be present and MUST",Object(l.b)("br",null),"match those in the certificate.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb logo_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"LogoURI is an URL string that references a logo for the client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb metadata"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonrawmessage"},"JSONRawMessage")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb owner"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Owner is a string identifying the owner of the OAuth 2.0 Client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb policy_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"PolicyURI is a URL string that points to a human-readable privacy policy document",Object(l.b)("br",null),"that describes how the deployment organization collects, uses,",Object(l.b)("br",null),"retains, and discloses personal data.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb post_logout_redirect_uris"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb redirect_uris"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb request_object_signing_alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JWS ","[JWS]"," alg algorithm ","[JWA]"," that MUST be used for signing Request Objects sent to the OP. All Request Objects",Object(l.b)("br",null),"from this Client MUST be rejected, if not signed with this algorithm.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb request_uris"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb response_types"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb scope"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Scope is a string containing a space-separated list of scope values (as",Object(l.b)("br",null),"described in Section 3.3 of OAuth 2.0 ","[RFC6749]",") that the client",Object(l.b)("br",null),"can use when requesting access tokens.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb sector_identifier_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL using the https scheme to be used in calculating Pseudonymous Identifiers by the OP. The URL references a",Object(l.b)("br",null),"file with a single JSON array of redirect_uri values.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb subject_type"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"SubjectType requested for responses to this Client. The subject_types_supported Discovery parameter contains a",Object(l.b)("br",null),"list of the supported subject_type values for this server. Valid types include ",Object(l.b)("inlineCode",{parentName:"td"},"pairwise")," and ",Object(l.b)("inlineCode",{parentName:"td"},"public"),".")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb token_endpoint_auth_method"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Requested Client Authentication method for the Token Endpoint. The options are client_secret_post,",Object(l.b)("br",null),"client_secret_basic, private_key_jwt, and none.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb token_endpoint_auth_signing_alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Requested Client Authentication signing algorithm for the Token Endpoint.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb tos_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"TermsOfServiceURI is a URL string that points to a human-readable terms of service",Object(l.b)("br",null),"document for the client that describes a contractual relationship",Object(l.b)("br",null),"between the end-user and the client that the end-user accepts when",Object(l.b)("br",null),"authorizing the client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb updated_at"),Object(l.b)("td",{parentName:"tr",align:null},"string(date-time)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"UpdatedAt returns the timestamp of the last update.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb userinfo_signed_response_alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JWS alg algorithm ","[JWA]"," REQUIRED for signing UserInfo Responses. If this is specified, the response will be JWT",Object(l.b)("br",null),"[JWT]"," serialized, and signed using JWS. The default, if omitted, is for the UserInfo Response to return the Claims",Object(l.b)("br",null),"as a UTF-8 encoded JSON object using the application/json content-type.")))),Object(l.b)("h5",{id:"examples-7"},"Examples"),Object(l.b)("h6",{id:"200-response-5"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'[\n {\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n }\n]\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-8"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /clients \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/clients", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/clients', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/clients");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/clients',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/clients',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdcreateOAuth2Client"}),Object(l.b)("h3",{id:"create-an-oauth-20-client"},"Create an OAuth 2.0 Client"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"POST /clients HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,"Create a new OAuth 2.0 client If you pass ",Object(l.b)("inlineCode",{parentName:"p"},"client_secret")," the secret will be\nused, otherwise a random secret will be generated. The secret will be returned\nin the response and you will not be able to retrieve it later on. Write the\nsecret down and keep it somwhere safe."),Object(l.b)("p",null,"OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows.\nUsually, OAuth 2.0 clients are generated for applications which want to consume\nyour OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will\nneed an OAuth 2.0 Client as well. Make sure that this endpoint is well protected\nand only callable by first-party components."),Object(l.b)("h4",{id:"request-body-2"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n}\n')),Object(l.b)("a",{id:"create-an-oauth-2.0-client-parameters"}),Object(l.b)("h4",{id:"parameters-3"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client")),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-9"},"Responses"),Object(l.b)("a",{id:"create-an-oauth-2.0-client-responses"}),Object(l.b)("h5",{id:"overview-9"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"201"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.2"},"Created")),Object(l.b)("td",{parentName:"tr",align:null},"oAuth2Client"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"400"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.1"},"Bad Request")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"409"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.8"},"Conflict")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-8"},"Examples"),Object(l.b)("h6",{id:"201-response"},"201 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-9"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X POST /clients \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("POST", "/clients", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "allowed_cors_origins": [\n "string"\n ],\n "audience": [\n "string"\n ],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": [\n "string"\n ],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": [\n "string"\n ],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": [\n "string"\n ],\n "redirect_uris": [\n "string"\n ],\n "request_object_signing_alg": "string",\n "request_uris": [\n "string"\n ],\n "response_types": [\n "string"\n ],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n}\';\nconst headers = {\n \'Content-Type\': \'application/json\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/clients\', {\n method: \'POST\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/clients");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("POST");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.post(\n '/clients',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.post '/clients',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdgetOAuth2Client"}),Object(l.b)("h3",{id:"get-an-oauth-20-client"},"Get an OAuth 2.0 Client."),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /clients/{id} HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"Get an OAUth 2.0 client by its ID. This endpoint never returns passwords."),Object(l.b)("p",null,"OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows.\nUsually, OAuth 2.0 clients are generated for applications which want to consume\nyour OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will\nneed an OAuth 2.0 Client as well. Make sure that this endpoint is well protected\nand only callable by first-party components."),Object(l.b)("a",{id:"get-an-oauth-2.0-client.-parameters"}),Object(l.b)("h4",{id:"parameters-4"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"id"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The id of the OAuth 2.0 Client.")))),Object(l.b)("h4",{id:"responses-10"},"Responses"),Object(l.b)("a",{id:"get-an-oauth-2.0-client.-responses"}),Object(l.b)("h5",{id:"overview-10"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"oAuth2Client"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-9"},"Examples"),Object(l.b)("h6",{id:"200-response-6"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-10"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /clients/{id} \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/clients/{id}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/clients/{id}', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/clients/{id}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/clients/{id}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/clients/{id}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdupdateOAuth2Client"}),Object(l.b)("h3",{id:"update-an-oauth-20-client"},"Update an OAuth 2.0 Client"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"PUT /clients/{id} HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,"Update an existing OAuth 2.0 Client. If you pass ",Object(l.b)("inlineCode",{parentName:"p"},"client_secret")," the secret will\nbe updated and returned via the API. This is the only time you will be able to\nretrieve the client secret, so write it down and keep it safe."),Object(l.b)("p",null,"OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows.\nUsually, OAuth 2.0 clients are generated for applications which want to consume\nyour OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will\nneed an OAuth 2.0 Client as well. Make sure that this endpoint is well protected\nand only callable by first-party components."),Object(l.b)("h4",{id:"request-body-3"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n}\n')),Object(l.b)("a",{id:"update-an-oauth-2.0-client-parameters"}),Object(l.b)("h4",{id:"parameters-5"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"id"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client")),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-11"},"Responses"),Object(l.b)("a",{id:"update-an-oauth-2.0-client-responses"}),Object(l.b)("h5",{id:"overview-11"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"oAuth2Client"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-10"},"Examples"),Object(l.b)("h6",{id:"200-response-7"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-11"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X PUT /clients/{id} \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("PUT", "/clients/{id}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "allowed_cors_origins": [\n "string"\n ],\n "audience": [\n "string"\n ],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": [\n "string"\n ],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": [\n "string"\n ],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": [\n "string"\n ],\n "redirect_uris": [\n "string"\n ],\n "request_object_signing_alg": "string",\n "request_uris": [\n "string"\n ],\n "response_types": [\n "string"\n ],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n}\';\nconst headers = {\n \'Content-Type\': \'application/json\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/clients/{id}\', {\n method: \'PUT\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/clients/{id}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("PUT");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.put(\n '/clients/{id}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.put '/clients/{id}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIddeleteOAuth2Client"}),Object(l.b)("h3",{id:"deletes-an-oauth-20-client"},"Deletes an OAuth 2.0 Client"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"DELETE /clients/{id} HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"Delete an existing OAuth 2.0 Client by its ID."),Object(l.b)("p",null,"OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows.\nUsually, OAuth 2.0 clients are generated for applications which want to consume\nyour OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will\nneed an OAuth 2.0 Client as well. Make sure that this endpoint is well protected\nand only callable by first-party components."),Object(l.b)("a",{id:"deletes-an-oauth-2.0-client-parameters"}),Object(l.b)("h4",{id:"parameters-6"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"id"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The id of the OAuth 2.0 Client.")))),Object(l.b)("h4",{id:"responses-12"},"Responses"),Object(l.b)("a",{id:"deletes-an-oauth-2.0-client-responses"}),Object(l.b)("h5",{id:"overview-12"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"204"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.5"},"No Content")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-11"},"Examples"),Object(l.b)("h6",{id:"404-response"},"404 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-12"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X DELETE /clients/{id} \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("DELETE", "/clients/{id}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/clients/{id}', {\n method: 'DELETE',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/clients/{id}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("DELETE");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.delete(\n '/clients/{id}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.delete '/clients/{id}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdisInstanceAlive"}),Object(l.b)("h3",{id:"check-alive-status"},"Check Alive Status"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /health/alive HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint returns a 200 status code when the HTTP server is up running. This\nstatus does currently not include checks whether the database connection is\nworking."),Object(l.b)("p",null,"If the service supports TLS Edge Termination, this endpoint does not require the\n",Object(l.b)("inlineCode",{parentName:"p"},"X-Forwarded-Proto")," header to be set."),Object(l.b)("p",null,"Be aware that if you are running multiple nodes of this service, the health\nstatus will never refer to the cluster state, only to a single instance."),Object(l.b)("h4",{id:"responses-13"},"Responses"),Object(l.b)("a",{id:"check-alive-status-responses"}),Object(l.b)("h5",{id:"overview-13"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"healthStatus"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemahealthstatus"},"healthStatus"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-12"},"Examples"),Object(l.b)("h6",{id:"200-response-8"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "status": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-13"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /health/alive \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/health/alive", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/health/alive', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/health/alive");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/health/alive',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/health/alive',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdgetJsonWebKeySet"}),Object(l.b)("h3",{id:"retrieve-a-json-web-key-set"},"Retrieve a JSON Web Key Set"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /keys/{set} HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint can be used to retrieve JWK Sets stored in ORY Hydra."),Object(l.b)("p",null,"A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that\nrepresents a cryptographic key. A JWK Set is a JSON data structure that\nrepresents a set of JWKs. A JSON Web Key is identified by its set and key id.\nORY Hydra uses this functionality to store cryptographic keys used for TLS and\nJSON Web Tokens (such as OpenID Connect ID tokens), and allows storing\nuser-defined keys as well."),Object(l.b)("a",{id:"retrieve-a-json-web-key-set-parameters"}),Object(l.b)("h4",{id:"parameters-7"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"set"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The set")))),Object(l.b)("h4",{id:"responses-14"},"Responses"),Object(l.b)("a",{id:"retrieve-a-json-web-key-set-responses"}),Object(l.b)("h5",{id:"overview-14"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"JSONWebKeySet"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkeyset"},"JSONWebKeySet"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"403"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.3"},"Forbidden")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-13"},"Examples"),Object(l.b)("h6",{id:"200-response-9"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "keys": [\n {\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n }\n ]\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-14"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /keys/{set} \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/keys/{set}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/keys/{set}', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/keys/{set}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/keys/{set}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/keys/{set}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdupdateJsonWebKeySet"}),Object(l.b)("h3",{id:"update-a-json-web-key-set"},"Update a JSON Web Key Set"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"PUT /keys/{set} HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,"Use this method if you do not want to let Hydra generate the JWKs for you, but\ninstead save your own."),Object(l.b)("p",null,"A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that\nrepresents a cryptographic key. A JWK Set is a JSON data structure that\nrepresents a set of JWKs. A JSON Web Key is identified by its set and key id.\nORY Hydra uses this functionality to store cryptographic keys used for TLS and\nJSON Web Tokens (such as OpenID Connect ID tokens), and allows storing\nuser-defined keys as well."),Object(l.b)("h4",{id:"request-body-4"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "keys": [\n {\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n }\n ]\n}\n')),Object(l.b)("a",{id:"update-a-json-web-key-set-parameters"}),Object(l.b)("h4",{id:"parameters-8"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"set"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The set")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkeyset"},"JSONWebKeySet")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-15"},"Responses"),Object(l.b)("a",{id:"update-a-json-web-key-set-responses"}),Object(l.b)("h5",{id:"overview-15"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"JSONWebKeySet"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkeyset"},"JSONWebKeySet"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"403"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.3"},"Forbidden")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-14"},"Examples"),Object(l.b)("h6",{id:"200-response-10"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "keys": [\n {\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n }\n ]\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-15"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X PUT /keys/{set} \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("PUT", "/keys/{set}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "keys": [\n {\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": [\n "string"\n ],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n }\n ]\n}\';\nconst headers = {\n \'Content-Type\': \'application/json\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/keys/{set}\', {\n method: \'PUT\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/keys/{set}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("PUT");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.put(\n '/keys/{set}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.put '/keys/{set}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdcreateJsonWebKeySet"}),Object(l.b)("h3",{id:"generate-a-new-json-web-key"},"Generate a New JSON Web Key"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"POST /keys/{set} HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint is capable of generating JSON Web Key Sets for you. There a\ndifferent strategies available, such as symmetric cryptographic keys (HS256,\nHS512) and asymetric cryptographic keys (RS256, ECDSA). If the specified JSON\nWeb Key Set does not exist, it will be created."),Object(l.b)("p",null,"A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that\nrepresents a cryptographic key. A JWK Set is a JSON data structure that\nrepresents a set of JWKs. A JSON Web Key is identified by its set and key id.\nORY Hydra uses this functionality to store cryptographic keys used for TLS and\nJSON Web Tokens (such as OpenID Connect ID tokens), and allows storing\nuser-defined keys as well."),Object(l.b)("h4",{id:"request-body-5"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "alg": "string",\n "kid": "string",\n "use": "string"\n}\n')),Object(l.b)("a",{id:"generate-a-new-json-web-key-parameters"}),Object(l.b)("h4",{id:"parameters-9"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"set"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The set")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkeysetgeneratorrequest"},"jsonWebKeySetGeneratorRequest")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-16"},"Responses"),Object(l.b)("a",{id:"generate-a-new-json-web-key-responses"}),Object(l.b)("h5",{id:"overview-16"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"201"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.2"},"Created")),Object(l.b)("td",{parentName:"tr",align:null},"JSONWebKeySet"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkeyset"},"JSONWebKeySet"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"403"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.3"},"Forbidden")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-15"},"Examples"),Object(l.b)("h6",{id:"201-response-1"},"201 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "keys": [\n {\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n }\n ]\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-16"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X POST /keys/{set} \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("POST", "/keys/{set}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch');\nconst input = '{\n \"alg\": \"string\",\n \"kid\": \"string\",\n \"use\": \"string\"\n}';\nconst headers = {\n 'Content-Type': 'application/json', 'Accept': 'application/json'\n}\n\nfetch('/keys/{set}', {\n method: 'POST',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/keys/{set}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("POST");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.post(\n '/keys/{set}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.post '/keys/{set}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIddeleteJsonWebKeySet"}),Object(l.b)("h3",{id:"delete-a-json-web-key-set"},"Delete a JSON Web Key Set"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"DELETE /keys/{set} HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"Use this endpoint to delete a complete JSON Web Key Set and all the keys in that\nset."),Object(l.b)("p",null,"A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that\nrepresents a cryptographic key. A JWK Set is a JSON data structure that\nrepresents a set of JWKs. A JSON Web Key is identified by its set and key id.\nORY Hydra uses this functionality to store cryptographic keys used for TLS and\nJSON Web Tokens (such as OpenID Connect ID tokens), and allows storing\nuser-defined keys as well."),Object(l.b)("a",{id:"delete-a-json-web-key-set-parameters"}),Object(l.b)("h4",{id:"parameters-10"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"set"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The set")))),Object(l.b)("h4",{id:"responses-17"},"Responses"),Object(l.b)("a",{id:"delete-a-json-web-key-set-responses"}),Object(l.b)("h5",{id:"overview-17"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"204"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.5"},"No Content")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"403"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.3"},"Forbidden")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-16"},"Examples"),Object(l.b)("h6",{id:"401-response-2"},"401 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-17"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X DELETE /keys/{set} \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("DELETE", "/keys/{set}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/keys/{set}', {\n method: 'DELETE',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/keys/{set}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("DELETE");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.delete(\n '/keys/{set}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.delete '/keys/{set}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdgetJsonWebKey"}),Object(l.b)("h3",{id:"fetch-a-json-web-key"},"Fetch a JSON Web Key"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /keys/{set}/{kid} HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint returns a singular JSON Web Key, identified by the set and the\nspecific key ID (kid)."),Object(l.b)("a",{id:"fetch-a-json-web-key-parameters"}),Object(l.b)("h4",{id:"parameters-11"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"kid"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The kid of the desired key")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"set"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The set")))),Object(l.b)("h4",{id:"responses-18"},"Responses"),Object(l.b)("a",{id:"fetch-a-json-web-key-responses"}),Object(l.b)("h5",{id:"overview-18"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"JSONWebKeySet"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkeyset"},"JSONWebKeySet"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-17"},"Examples"),Object(l.b)("h6",{id:"200-response-11"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "keys": [\n {\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n }\n ]\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-18"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /keys/{set}/{kid} \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/keys/{set}/{kid}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/keys/{set}/{kid}', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/keys/{set}/{kid}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/keys/{set}/{kid}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/keys/{set}/{kid}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdupdateJsonWebKey"}),Object(l.b)("h3",{id:"update-a-json-web-key"},"Update a JSON Web Key"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"PUT /keys/{set}/{kid} HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,"Use this method if you do not want to let Hydra generate the JWKs for you, but\ninstead save your own."),Object(l.b)("p",null,"A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that\nrepresents a cryptographic key. A JWK Set is a JSON data structure that\nrepresents a set of JWKs. A JSON Web Key is identified by its set and key id.\nORY Hydra uses this functionality to store cryptographic keys used for TLS and\nJSON Web Tokens (such as OpenID Connect ID tokens), and allows storing\nuser-defined keys as well."),Object(l.b)("h4",{id:"request-body-6"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n}\n')),Object(l.b)("a",{id:"update-a-json-web-key-parameters"}),Object(l.b)("h4",{id:"parameters-12"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"kid"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The kid of the desired key")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"set"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The set")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkey"},"JSONWebKey")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-19"},"Responses"),Object(l.b)("a",{id:"update-a-json-web-key-responses"}),Object(l.b)("h5",{id:"overview-19"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"JSONWebKey"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkey"},"JSONWebKey"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"403"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.3"},"Forbidden")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-18"},"Examples"),Object(l.b)("h6",{id:"200-response-12"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-19"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X PUT /keys/{set}/{kid} \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("PUT", "/keys/{set}/{kid}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": [\n "string"\n ],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n}\';\nconst headers = {\n \'Content-Type\': \'application/json\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/keys/{set}/{kid}\', {\n method: \'PUT\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/keys/{set}/{kid}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("PUT");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.put(\n '/keys/{set}/{kid}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.put '/keys/{set}/{kid}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIddeleteJsonWebKey"}),Object(l.b)("h3",{id:"delete-a-json-web-key"},"Delete a JSON Web Key"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"DELETE /keys/{set}/{kid} HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"Use this endpoint to delete a single JSON Web Key."),Object(l.b)("p",null,"A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that\nrepresents a cryptographic key. A JWK Set is a JSON data structure that\nrepresents a set of JWKs. A JSON Web Key is identified by its set and key id.\nORY Hydra uses this functionality to store cryptographic keys used for TLS and\nJSON Web Tokens (such as OpenID Connect ID tokens), and allows storing\nuser-defined keys as well."),Object(l.b)("a",{id:"delete-a-json-web-key-parameters"}),Object(l.b)("h4",{id:"parameters-13"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"kid"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The kid of the desired key")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"set"),Object(l.b)("td",{parentName:"tr",align:null},"path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The set")))),Object(l.b)("h4",{id:"responses-20"},"Responses"),Object(l.b)("a",{id:"delete-a-json-web-key-responses"}),Object(l.b)("h5",{id:"overview-20"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"204"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.5"},"No Content")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"403"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.3"},"Forbidden")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-19"},"Examples"),Object(l.b)("h6",{id:"401-response-3"},"401 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-20"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X DELETE /keys/{set}/{kid} \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("DELETE", "/keys/{set}/{kid}", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/keys/{set}/{kid}', {\n method: 'DELETE',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/keys/{set}/{kid}");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("DELETE");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.delete(\n '/keys/{set}/{kid}',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.delete '/keys/{set}/{kid}',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdprometheus"}),Object(l.b)("h3",{id:"get-snapshot-metrics-from-the-hydra-service"},"Get Snapshot Metrics from the Hydra Service."),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /metrics/prometheus HTTP/1.1\n\n")),Object(l.b)("p",null,"If you're using k8s, you can then add annotations to your deployment like so:"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},'metadata:\nannotations:\nprometheus.io/port: "4445"\nprometheus.io/path: "/metrics/prometheus"\n')),Object(l.b)("p",null,"If the service supports TLS Edge Termination, this endpoint does not require the\n",Object(l.b)("inlineCode",{parentName:"p"},"X-Forwarded-Proto")," header to be set."),Object(l.b)("h4",{id:"responses-21"},"Responses"),Object(l.b)("a",{id:"get-snapshot-metrics-from-the-hydra-service.-responses"}),Object(l.b)("h5",{id:"overview-21"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")))),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-21"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /metrics/prometheus\n\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/metrics/prometheus", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nfetch('/metrics/prometheus', {\n method: 'GET'\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/metrics/prometheus");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nr = requests.get(\n '/metrics/prometheus',\n params={)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nresult = RestClient.get '/metrics/prometheus',\n params: {}\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdgetConsentRequest"}),Object(l.b)("h3",{id:"get-consent-request-information"},"Get Consent Request Information"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /oauth2/auth/requests/consent?consent_challenge=string HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY\nHydra asks the login provider to authenticate the subject and then tell ORY\nHydra now about it. If the subject authenticated, he/she must now be asked if\nthe OAuth 2.0 Client which initiated the flow should be allowed to access the\nresources on the subject's behalf."),Object(l.b)("p",null,'The consent provider which handles this request and is a web app implemented and\nhosted by you. It shows a subject interface which asks the subject to grant or\ndeny the client access to the requested scope ("Application my-dropbox-app wants\nwrite access to all your private files").'),Object(l.b)("p",null,"The consent challenge is appended to the consent provider's URL to which the\nsubject's user-agent (browser) is redirected to. The consent provider uses that\nchallenge to fetch information on the OAuth2 request and then tells ORY Hydra if\nthe subject accepted or rejected the request."),Object(l.b)("a",{id:"get-consent-request-information-parameters"}),Object(l.b)("h4",{id:"parameters-14"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"consent_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-22"},"Responses"),Object(l.b)("a",{id:"get-consent-request-information-responses"}),Object(l.b)("h5",{id:"overview-22"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"consentRequest"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaconsentrequest"},"consentRequest"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"409"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.8"},"Conflict")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-20"},"Examples"),Object(l.b)("h6",{id:"200-response-13"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "acr": "string",\n "challenge": "string",\n "client": {\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n },\n "context": {},\n "login_challenge": "string",\n "login_session_id": "string",\n "oidc_context": {\n "acr_values": ["string"],\n "display": "string",\n "id_token_hint_claims": {},\n "login_hint": "string",\n "ui_locales": ["string"]\n },\n "request_url": "string",\n "requested_access_token_audience": ["string"],\n "requested_scope": ["string"],\n "skip": true,\n "subject": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-22"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /oauth2/auth/requests/consent?consent_challenge=string \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/oauth2/auth/requests/consent", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/oauth2/auth/requests/consent?consent_challenge=string', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/requests/consent?consent_challenge=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/oauth2/auth/requests/consent',\n params={\n 'consent_challenge': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/oauth2/auth/requests/consent',\n params: {\n 'consent_challenge' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdacceptConsentRequest"}),Object(l.b)("h3",{id:"accept-a-consent-request"},"Accept a Consent Request"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"PUT /oauth2/auth/requests/consent/accept?consent_challenge=string HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,"When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY\nHydra asks the login provider to authenticate the subject and then tell ORY\nHydra now about it. If the subject authenticated, he/she must now be asked if\nthe OAuth 2.0 Client which initiated the flow should be allowed to access the\nresources on the subject's behalf."),Object(l.b)("p",null,'The consent provider which handles this request and is a web app implemented and\nhosted by you. It shows a subject interface which asks the subject to grant or\ndeny the client access to the requested scope ("Application my-dropbox-app wants\nwrite access to all your private files").'),Object(l.b)("p",null,"The consent challenge is appended to the consent provider's URL to which the\nsubject's user-agent (browser) is redirected to. The consent provider uses that\nchallenge to fetch information on the OAuth2 request and then tells ORY Hydra if\nthe subject accepted or rejected the request."),Object(l.b)("p",null,"This endpoint tells ORY Hydra that the subject has authorized the OAuth 2.0\nclient to access resources on his/her behalf. The consent provider includes\nadditional information, such as session data for access and ID tokens, and if\nthe consent request should be used as basis for future requests."),Object(l.b)("p",null,"The response contains a redirect URL which the consent provider should redirect\nthe user-agent to."),Object(l.b)("h4",{id:"request-body-7"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "grant_access_token_audience": ["string"],\n "grant_scope": ["string"],\n "handled_at": "2019-08-24T14:15:22Z",\n "remember": true,\n "remember_for": 0,\n "session": {\n "access_token": {},\n "id_token": {}\n }\n}\n')),Object(l.b)("a",{id:"accept-a-consent-request-parameters"}),Object(l.b)("h4",{id:"parameters-15"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"consent_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaacceptconsentrequest"},"acceptConsentRequest")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-23"},"Responses"),Object(l.b)("a",{id:"accept-a-consent-request-responses"}),Object(l.b)("h5",{id:"overview-23"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"completedRequest"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemacompletedrequest"},"completedRequest"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-21"},"Examples"),Object(l.b)("h6",{id:"200-response-14"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "redirect_to": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-23"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X PUT /oauth2/auth/requests/consent/accept?consent_challenge=string \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("PUT", "/oauth2/auth/requests/consent/accept", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "grant_access_token_audience": [\n "string"\n ],\n "grant_scope": [\n "string"\n ],\n "handled_at": "2019-08-24T14:15:22Z",\n "remember": true,\n "remember_for": 0,\n "session": {\n "access_token": {},\n "id_token": {}\n }\n}\';\nconst headers = {\n \'Content-Type\': \'application/json\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/oauth2/auth/requests/consent/accept?consent_challenge=string\', {\n method: \'PUT\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/requests/consent/accept?consent_challenge=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("PUT");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.put(\n '/oauth2/auth/requests/consent/accept',\n params={\n 'consent_challenge': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.put '/oauth2/auth/requests/consent/accept',\n params: {\n 'consent_challenge' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdrejectConsentRequest"}),Object(l.b)("h3",{id:"reject-a-consent-request"},"Reject a Consent Request"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"PUT /oauth2/auth/requests/consent/reject?consent_challenge=string HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,"When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY\nHydra asks the login provider to authenticate the subject and then tell ORY\nHydra now about it. If the subject authenticated, he/she must now be asked if\nthe OAuth 2.0 Client which initiated the flow should be allowed to access the\nresources on the subject's behalf."),Object(l.b)("p",null,'The consent provider which handles this request and is a web app implemented and\nhosted by you. It shows a subject interface which asks the subject to grant or\ndeny the client access to the requested scope ("Application my-dropbox-app wants\nwrite access to all your private files").'),Object(l.b)("p",null,"The consent challenge is appended to the consent provider's URL to which the\nsubject's user-agent (browser) is redirected to. The consent provider uses that\nchallenge to fetch information on the OAuth2 request and then tells ORY Hydra if\nthe subject accepted or rejected the request."),Object(l.b)("p",null,"This endpoint tells ORY Hydra that the subject has not authorized the OAuth 2.0\nclient to access resources on his/her behalf. The consent provider must include\na reason why the consent was not granted."),Object(l.b)("p",null,"The response contains a redirect URL which the consent provider should redirect\nthe user-agent to."),Object(l.b)("h4",{id:"request-body-8"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "error": "string",\n "error_debug": "string",\n "error_description": "string",\n "error_hint": "string",\n "status_code": 0\n}\n')),Object(l.b)("a",{id:"reject-a-consent-request-parameters"}),Object(l.b)("h4",{id:"parameters-16"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"consent_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemarejectrequest"},"rejectRequest")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-24"},"Responses"),Object(l.b)("a",{id:"reject-a-consent-request-responses"}),Object(l.b)("h5",{id:"overview-24"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"completedRequest"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemacompletedrequest"},"completedRequest"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-22"},"Examples"),Object(l.b)("h6",{id:"200-response-15"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "redirect_to": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-24"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X PUT /oauth2/auth/requests/consent/reject?consent_challenge=string \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("PUT", "/oauth2/auth/requests/consent/reject", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "error": "string",\n "error_debug": "string",\n "error_description": "string",\n "error_hint": "string",\n "status_code": 0\n}\';\nconst headers = {\n \'Content-Type\': \'application/json\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/oauth2/auth/requests/consent/reject?consent_challenge=string\', {\n method: \'PUT\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/requests/consent/reject?consent_challenge=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("PUT");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.put(\n '/oauth2/auth/requests/consent/reject',\n params={\n 'consent_challenge': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.put '/oauth2/auth/requests/consent/reject',\n params: {\n 'consent_challenge' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdgetLoginRequest"}),Object(l.b)("h3",{id:"get-a-login-request"},"Get a Login Request"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /oauth2/auth/requests/login?login_challenge=string HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,'When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY\nHydra asks the login provider (sometimes called "identity provider") to\nauthenticate the subject and then tell ORY Hydra now about it. The login\nprovider is an web-app you write and host, and it must be able to authenticate\n("show the subject a login screen") a subject (in OAuth2 the proper name for\nsubject is "resource owner").'),Object(l.b)("p",null,"The authentication challenge is appended to the login provider URL to which the\nsubject's user-agent (browser) is redirected to. The login provider uses that\nchallenge to fetch information on the OAuth2 request and then accept or reject\nthe requested authentication process."),Object(l.b)("a",{id:"get-a-login-request-parameters"}),Object(l.b)("h4",{id:"parameters-17"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"login_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-25"},"Responses"),Object(l.b)("a",{id:"get-a-login-request-responses"}),Object(l.b)("h5",{id:"overview-25"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"loginRequest"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaloginrequest"},"loginRequest"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"400"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.1"},"Bad Request")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"409"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.8"},"Conflict")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-23"},"Examples"),Object(l.b)("h6",{id:"200-response-16"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "challenge": "string",\n "client": {\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n },\n "oidc_context": {\n "acr_values": ["string"],\n "display": "string",\n "id_token_hint_claims": {},\n "login_hint": "string",\n "ui_locales": ["string"]\n },\n "request_url": "string",\n "requested_access_token_audience": ["string"],\n "requested_scope": ["string"],\n "session_id": "string",\n "skip": true,\n "subject": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-25"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /oauth2/auth/requests/login?login_challenge=string \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/oauth2/auth/requests/login", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/oauth2/auth/requests/login?login_challenge=string', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/requests/login?login_challenge=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/oauth2/auth/requests/login',\n params={\n 'login_challenge': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/oauth2/auth/requests/login',\n params: {\n 'login_challenge' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdacceptLoginRequest"}),Object(l.b)("h3",{id:"accept-a-login-request"},"Accept a Login Request"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"PUT /oauth2/auth/requests/login/accept?login_challenge=string HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,'When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY\nHydra asks the login provider (sometimes called "identity provider") to\nauthenticate the subject and then tell ORY Hydra now about it. The login\nprovider is an web-app you write and host, and it must be able to authenticate\n("show the subject a login screen") a subject (in OAuth2 the proper name for\nsubject is "resource owner").'),Object(l.b)("p",null,"The authentication challenge is appended to the login provider URL to which the\nsubject's user-agent (browser) is redirected to. The login provider uses that\nchallenge to fetch information on the OAuth2 request and then accept or reject\nthe requested authentication process."),Object(l.b)("p",null,"This endpoint tells ORY Hydra that the subject has successfully authenticated\nand includes additional information such as the subject's ID and if ORY Hydra\nshould remember the subject's subject agent for future authentication attempts\nby setting a cookie."),Object(l.b)("p",null,"The response contains a redirect URL which the login provider should redirect\nthe user-agent to."),Object(l.b)("h4",{id:"request-body-9"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "acr": "string",\n "context": {},\n "force_subject_identifier": "string",\n "remember": true,\n "remember_for": 0,\n "subject": "string"\n}\n')),Object(l.b)("a",{id:"accept-a-login-request-parameters"}),Object(l.b)("h4",{id:"parameters-18"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"login_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaacceptloginrequest"},"acceptLoginRequest")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-26"},"Responses"),Object(l.b)("a",{id:"accept-a-login-request-responses"}),Object(l.b)("h5",{id:"overview-26"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"completedRequest"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemacompletedrequest"},"completedRequest"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"400"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.1"},"Bad Request")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-24"},"Examples"),Object(l.b)("h6",{id:"200-response-17"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "redirect_to": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-26"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X PUT /oauth2/auth/requests/login/accept?login_challenge=string \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("PUT", "/oauth2/auth/requests/login/accept", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "acr": "string",\n "context": {},\n "force_subject_identifier": "string",\n "remember": true,\n "remember_for": 0,\n "subject": "string"\n}\';\nconst headers = {\n \'Content-Type\': \'application/json\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/oauth2/auth/requests/login/accept?login_challenge=string\', {\n method: \'PUT\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/requests/login/accept?login_challenge=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("PUT");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.put(\n '/oauth2/auth/requests/login/accept',\n params={\n 'login_challenge': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.put '/oauth2/auth/requests/login/accept',\n params: {\n 'login_challenge' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdrejectLoginRequest"}),Object(l.b)("h3",{id:"reject-a-login-request"},"Reject a Login Request"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"PUT /oauth2/auth/requests/login/reject?login_challenge=string HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,'When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY\nHydra asks the login provider (sometimes called "identity provider") to\nauthenticate the subject and then tell ORY Hydra now about it. The login\nprovider is an web-app you write and host, and it must be able to authenticate\n("show the subject a login screen") a subject (in OAuth2 the proper name for\nsubject is "resource owner").'),Object(l.b)("p",null,"The authentication challenge is appended to the login provider URL to which the\nsubject's user-agent (browser) is redirected to. The login provider uses that\nchallenge to fetch information on the OAuth2 request and then accept or reject\nthe requested authentication process."),Object(l.b)("p",null,"This endpoint tells ORY Hydra that the subject has not authenticated and\nincludes a reason why the authentication was be denied."),Object(l.b)("p",null,"The response contains a redirect URL which the login provider should redirect\nthe user-agent to."),Object(l.b)("h4",{id:"request-body-10"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "error": "string",\n "error_debug": "string",\n "error_description": "string",\n "error_hint": "string",\n "status_code": 0\n}\n')),Object(l.b)("a",{id:"reject-a-login-request-parameters"}),Object(l.b)("h4",{id:"parameters-19"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"login_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemarejectrequest"},"rejectRequest")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-27"},"Responses"),Object(l.b)("a",{id:"reject-a-login-request-responses"}),Object(l.b)("h5",{id:"overview-27"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"completedRequest"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemacompletedrequest"},"completedRequest"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"400"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.1"},"Bad Request")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-25"},"Examples"),Object(l.b)("h6",{id:"200-response-18"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "redirect_to": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-27"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X PUT /oauth2/auth/requests/login/reject?login_challenge=string \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("PUT", "/oauth2/auth/requests/login/reject", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "error": "string",\n "error_debug": "string",\n "error_description": "string",\n "error_hint": "string",\n "status_code": 0\n}\';\nconst headers = {\n \'Content-Type\': \'application/json\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/oauth2/auth/requests/login/reject?login_challenge=string\', {\n method: \'PUT\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/requests/login/reject?login_challenge=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("PUT");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.put(\n '/oauth2/auth/requests/login/reject',\n params={\n 'login_challenge': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.put '/oauth2/auth/requests/login/reject',\n params: {\n 'login_challenge' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdgetLogoutRequest"}),Object(l.b)("h3",{id:"get-a-logout-request"},"Get a Logout Request"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /oauth2/auth/requests/logout?logout_challenge=string HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"Use this endpoint to fetch a logout request."),Object(l.b)("a",{id:"get-a-logout-request-parameters"}),Object(l.b)("h4",{id:"parameters-20"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"logout_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-28"},"Responses"),Object(l.b)("a",{id:"get-a-logout-request-responses"}),Object(l.b)("h5",{id:"overview-28"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"logoutRequest"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemalogoutrequest"},"logoutRequest"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-26"},"Examples"),Object(l.b)("h6",{id:"200-response-19"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "request_url": "string",\n "rp_initiated": true,\n "sid": "string",\n "subject": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-28"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /oauth2/auth/requests/logout?logout_challenge=string \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/oauth2/auth/requests/logout", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/oauth2/auth/requests/logout?logout_challenge=string', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/requests/logout?logout_challenge=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/oauth2/auth/requests/logout',\n params={\n 'logout_challenge': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/oauth2/auth/requests/logout',\n params: {\n 'logout_challenge' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdacceptLogoutRequest"}),Object(l.b)("h3",{id:"accept-a-logout-request"},"Accept a Logout Request"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"PUT /oauth2/auth/requests/logout/accept?logout_challenge=string HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"When a user or an application requests ORY Hydra to log out a user, this\nendpoint is used to confirm that logout request. No body is required."),Object(l.b)("p",null,"The response contains a redirect URL which the consent provider should redirect\nthe user-agent to."),Object(l.b)("a",{id:"accept-a-logout-request-parameters"}),Object(l.b)("h4",{id:"parameters-21"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"logout_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-29"},"Responses"),Object(l.b)("a",{id:"accept-a-logout-request-responses"}),Object(l.b)("h5",{id:"overview-29"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"completedRequest"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemacompletedrequest"},"completedRequest"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-27"},"Examples"),Object(l.b)("h6",{id:"200-response-20"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "redirect_to": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-29"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X PUT /oauth2/auth/requests/logout/accept?logout_challenge=string \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("PUT", "/oauth2/auth/requests/logout/accept", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/oauth2/auth/requests/logout/accept?logout_challenge=string', {\n method: 'PUT',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/requests/logout/accept?logout_challenge=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("PUT");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.put(\n '/oauth2/auth/requests/logout/accept',\n params={\n 'logout_challenge': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.put '/oauth2/auth/requests/logout/accept',\n params: {\n 'logout_challenge' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdrejectLogoutRequest"}),Object(l.b)("h3",{id:"reject-a-logout-request"},"Reject a Logout Request"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"PUT /oauth2/auth/requests/logout/reject?logout_challenge=string HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,"When a user or an application requests ORY Hydra to log out a user, this\nendpoint is used to deny that logout request. No body is required."),Object(l.b)("p",null,"The response is empty as the logout provider has to chose what action to perform\nnext."),Object(l.b)("h4",{id:"request-body-11"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "error": "string",\n "error_debug": "string",\n "error_description": "string",\n "error_hint": "string",\n "status_code": 0\n}\n')),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-yaml"},"error: string\nerror_debug: string\nerror_description: string\nerror_hint: string\nstatus_code: 0\n")),Object(l.b)("a",{id:"reject-a-logout-request-parameters"}),Object(l.b)("h4",{id:"parameters-22"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"logout_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemarejectrequest"},"rejectRequest")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-30"},"Responses"),Object(l.b)("a",{id:"reject-a-logout-request-responses"}),Object(l.b)("h5",{id:"overview-30"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"204"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.5"},"No Content")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"404"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.4"},"Not Found")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-28"},"Examples"),Object(l.b)("h6",{id:"404-response-1"},"404 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-30"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X PUT /oauth2/auth/requests/logout/reject?logout_challenge=string \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("PUT", "/oauth2/auth/requests/logout/reject", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},'const fetch = require(\'node-fetch\');\nconst input = \'{\n "error": "string",\n "error_debug": "string",\n "error_description": "string",\n "error_hint": "string",\n "status_code": 0\n}\';\nconst headers = {\n \'Content-Type\': \'application/json\', \'Accept\': \'application/json\'\n}\n\nfetch(\'/oauth2/auth/requests/logout/reject?logout_challenge=string\', {\n method: \'PUT\',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n'))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/requests/logout/reject?logout_challenge=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("PUT");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.put(\n '/oauth2/auth/requests/logout/reject',\n params={\n 'logout_challenge': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.put '/oauth2/auth/requests/logout/reject',\n params: {\n 'logout_challenge' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdlistSubjectConsentSessions"}),Object(l.b)("h3",{id:"lists-all-consent-sessions-of-a-subject"},"Lists All Consent Sessions of a Subject"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /oauth2/auth/sessions/consent?subject=string HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint lists all subject's granted consent sessions, including client and\ngranted scope. If the subject is unknown or has not granted any consent sessions\nyet, the endpoint returns an empty JSON array with status code 200 OK."),Object(l.b)("p",null,'The "Link" header is also included in successful responses, which contains one\nor more links for pagination, formatted like so:\n\'',Object(l.b)("a",{parentName:"p",href:"https://hydra-url/admin/oauth2/auth/sessions/consent?subject=%7Buser%7D&limit=%7Blimit%7D&offset=%7Boffset%7D"},"https://hydra-url/admin/oauth2/auth/sessions/consent?subject={user}&limit={limit}&offset={offset}"),";\nrel=\"{page}\"', where page is one of the following applicable pages: 'first',\n'next', 'last', and 'previous'. Multiple links can be included in this header,\nand will be separated by a comma."),Object(l.b)("a",{id:"lists-all-consent-sessions-of-a-subject-parameters"}),Object(l.b)("h4",{id:"parameters-23"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"subject"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-31"},"Responses"),Object(l.b)("a",{id:"lists-all-consent-sessions-of-a-subject-responses"}),Object(l.b)("h5",{id:"overview-31"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"A list of used consent requests."),Object(l.b)("td",{parentName:"tr",align:null},"Inline")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"400"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.1"},"Bad Request")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("a",{id:"lists-all-consent-sessions-of-a-subject-responseschema"}),Object(l.b)("h5",{id:"response-schema-1"},"Response Schema"),Object(l.b)("p",null,"Status Code ",Object(l.b)("strong",{parentName:"p"},"200")),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("em",{parentName:"td"},"anonymous")),Object(l.b)("td",{parentName:"tr",align:null},"[",Object(l.b)("a",{parentName:"td",href:"#schemapreviousconsentsession"},"PreviousConsentSession"),"]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"[The response used to return used consent requests",Object(l.b)("br",null),"same as HandledLoginRequest, just with consent_request exposed as json]")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb consent_request"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaconsentrequest"},"consentRequest")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb acr"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ACR represents the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it",Object(l.b)("br",null),"to express that, for example, a user authenticated using two factor authentication.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb challenge"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'ID is the identifier ("authorization challenge") of the consent authorization request. It is used to',Object(l.b)("br",null),"identify the session.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb client"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb allowed_cors_origins"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb audience"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb backchannel_logout_session_required"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the RP requires that a sid (session ID) Claim be included in the Logout",Object(l.b)("br",null),"Token to identify the RP session with the OP when the backchannel_logout_uri is used.",Object(l.b)("br",null),"If omitted, the default value is false.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb backchannel_logout_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RP URL that will cause the RP to log itself out when sent a Logout Token by the OP.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb client_id"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ID is the id for this client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb client_name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Name is the human-readable string name of the client to be presented to the",Object(l.b)("br",null),"end-user during authorization.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb client_secret"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Secret is the client's secret. The secret will be included in the create request as cleartext, and then",Object(l.b)("br",null),"never again. The secret is stored using BCrypt so it is impossible to recover it. Tell your users",Object(l.b)("br",null),"that they need to write the secret down as it will not be made available again.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb client_secret_expires_at"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"SecretExpiresAt is an integer holding the time at which the client",Object(l.b)("br",null),"secret will expire or 0 if it will not expire. The time is",Object(l.b)("br",null),"represented as the number of seconds from 1970-01-01T00:00:00Z as",Object(l.b)("br",null),"measured in UTC until the date/time of expiration.",Object(l.b)("br",null),Object(l.b)("br",null),"This feature is currently not supported and it's value will always",Object(l.b)("br",null),"be set to 0.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb client_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ClientURI is an URL string of a web page providing information about the client.",Object(l.b)("br",null),"If present, the server SHOULD display this URL to the end-user in",Object(l.b)("br",null),"a clickable fashion.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb contacts"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb created_at"),Object(l.b)("td",{parentName:"tr",align:null},"string(date-time)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"CreatedAt returns the timestamp of the client's creation.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb frontchannel_logout_session_required"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the RP requires that iss (issuer) and sid (session ID) query parameters be",Object(l.b)("br",null),"included to identify the RP session with the OP when the frontchannel_logout_uri is used.",Object(l.b)("br",null),"If omitted, the default value is false.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb frontchannel_logout_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RP URL that will cause the RP to log itself out when rendered in an iframe by the OP. An iss (issuer) query",Object(l.b)("br",null),"parameter and a sid (session ID) query parameter MAY be included by the OP to enable the RP to validate the",Object(l.b)("br",null),"request and to determine which of the potentially multiple sessions is to be logged out; if either is",Object(l.b)("br",null),"included, both MUST be.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb grant_types"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb jwks"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajosejsonwebkeyset"},"JoseJSONWebKeySet")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb jwks_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL for the Client's JSON Web Key Set ","[JWK]"," document. If the Client signs requests to the Server, it contains",Object(l.b)("br",null),"the signing key(s) the Server uses to validate signatures from the Client. The JWK Set MAY also contain the",Object(l.b)("br",null),"Client's encryption keys(s), which are used by the Server to encrypt responses to the Client. When both signing",Object(l.b)("br",null),"and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all keys in the referenced",Object(l.b)("br",null),"JWK Set to indicate each key's intended usage. Although some algorithms allow the same key to be used for both",Object(l.b)("br",null),"signatures and encryption, doing so is NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used",Object(l.b)("br",null),"to provide X.509 representations of keys provided. When used, the bare key values MUST still be present and MUST",Object(l.b)("br",null),"match those in the certificate.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb logo_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"LogoURI is an URL string that references a logo for the client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb metadata"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonrawmessage"},"JSONRawMessage")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb owner"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Owner is a string identifying the owner of the OAuth 2.0 Client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb policy_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"PolicyURI is a URL string that points to a human-readable privacy policy document",Object(l.b)("br",null),"that describes how the deployment organization collects, uses,",Object(l.b)("br",null),"retains, and discloses personal data.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb post_logout_redirect_uris"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb redirect_uris"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb request_object_signing_alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JWS ","[JWS]"," alg algorithm ","[JWA]"," that MUST be used for signing Request Objects sent to the OP. All Request Objects",Object(l.b)("br",null),"from this Client MUST be rejected, if not signed with this algorithm.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb request_uris"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb response_types"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb scope"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Scope is a string containing a space-separated list of scope values (as",Object(l.b)("br",null),"described in Section 3.3 of OAuth 2.0 ","[RFC6749]",") that the client",Object(l.b)("br",null),"can use when requesting access tokens.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb sector_identifier_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL using the https scheme to be used in calculating Pseudonymous Identifiers by the OP. The URL references a",Object(l.b)("br",null),"file with a single JSON array of redirect_uri values.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb subject_type"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"SubjectType requested for responses to this Client. The subject_types_supported Discovery parameter contains a",Object(l.b)("br",null),"list of the supported subject_type values for this server. Valid types include ",Object(l.b)("inlineCode",{parentName:"td"},"pairwise")," and ",Object(l.b)("inlineCode",{parentName:"td"},"public"),".")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb token_endpoint_auth_method"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Requested Client Authentication method for the Token Endpoint. The options are client_secret_post,",Object(l.b)("br",null),"client_secret_basic, private_key_jwt, and none.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb token_endpoint_auth_signing_alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Requested Client Authentication signing algorithm for the Token Endpoint.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb tos_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"TermsOfServiceURI is a URL string that points to a human-readable terms of service",Object(l.b)("br",null),"document for the client that describes a contractual relationship",Object(l.b)("br",null),"between the end-user and the client that the end-user accepts when",Object(l.b)("br",null),"authorizing the client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb updated_at"),Object(l.b)("td",{parentName:"tr",align:null},"string(date-time)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"UpdatedAt returns the timestamp of the last update.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb userinfo_signed_response_alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JWS alg algorithm ","[JWA]"," REQUIRED for signing UserInfo Responses. If this is specified, the response will be JWT",Object(l.b)("br",null),"[JWT]"," serialized, and signed using JWS. The default, if omitted, is for the UserInfo Response to return the Claims",Object(l.b)("br",null),"as a UTF-8 encoded JSON object using the application/json content-type.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb context"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonrawmessage"},"JSONRawMessage")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb login_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"LoginChallenge is the login challenge this consent challenge belongs to. It can be used to associate",Object(l.b)("br",null),"a login and consent request in the login & consent app.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb login_session_id"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"LoginSessionID is the login session ID. If the user-agent reuses a login session (via cookie / remember flag)",Object(l.b)("br",null),"this ID will remain the same. If the user-agent did not have an existing authentication session (e.g. remember is false)",Object(l.b)("br",null),'this will be a new random value. This value is used as the "sid" parameter in the ID Token and in OIDC Front-/Back-',Object(l.b)("br",null),"channel logout. It's value can generally be used to associate consecutive login requests by a certain user.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb oidc_context"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaopenidconnectcontext"},"openIDConnectContext")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb acr_values"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request.",Object(l.b)("br",null),"It is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required.",Object(l.b)("br",null),Object(l.b)("br",null),"OpenID Connect defines it as follows:",Object(l.b)("br",null),"> Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values",Object(l.b)("br",null),"that the Authorization Server is being requested to use for processing this Authentication Request, with the",Object(l.b)("br",null),"values appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication",Object(l.b)("br",null),"performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a",Object(l.b)("br",null),"Voluntary Claim by this parameter.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb display"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User.",Object(l.b)("br",null),"The defined values are:",Object(l.b)("br",null),"page: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode.",Object(l.b)("br",null),"popup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over.",Object(l.b)("br",null),"touch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface.",Object(l.b)("br",null),'wap: The Authorization Server SHOULD display the authentication and consent UI consistent with a "feature phone" type display.',Object(l.b)("br",null),Object(l.b)("br",null),"The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb id_token_hint_claims"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"IDTokenHintClaims are the claims of the ID Token previously issued by the Authorization Server being passed as a hint about the",Object(l.b)("br",null),"End-User's current or past authenticated session with the Client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb login_hint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"LoginHint hints about the login identifier the End-User might use to log in (if necessary).",Object(l.b)("br",null),"This hint can be used by an RP if it first asks the End-User for their e-mail address (or other identifier)",Object(l.b)("br",null),"and then wants to pass that value as a hint to the discovered authorization service. This value MAY also be a",Object(l.b)("br",null),"phone number in the format specified for the phone_number Claim. The use of this parameter is optional.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb\xbb ui_locales"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a",Object(l.b)("br",null),"space-separated list of BCP47 ","[RFC5646]"," language tag values, ordered by preference. For instance, the value",Object(l.b)("br",null),'"fr-CA fr en" represents a preference for French as spoken in Canada, then French (without a region designation),',Object(l.b)("br",null),"followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested",Object(l.b)("br",null),"locales are not supported by the OpenID Provider.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb request_url"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which",Object(l.b)("br",null),"initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but",Object(l.b)("br",null),"might come in handy if you want to deal with additional request parameters.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb requested_access_token_audience"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb requested_scope"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb skip"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Skip, if true, implies that the client has requested the same scopes from the same user previously.",Object(l.b)("br",null),"If true, you must not ask the user to grant the requested scopes. You must however either allow or deny the",Object(l.b)("br",null),"consent request using the usual API call.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb subject"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope",Object(l.b)("br",null),"requested by the OAuth 2.0 client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb grant_access_token_audience"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb grant_scope"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb handled_at"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemanulltime"},"NullTime"),"(date-time)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb remember"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same",Object(l.b)("br",null),"client asks the same user for the same, or a subset of, scope.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb remember_for"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RememberFor sets how long the consent authorization should be remembered for in seconds. If set to ",Object(l.b)("inlineCode",{parentName:"td"},"0"),", the",Object(l.b)("br",null),"authorization will be remembered indefinitely.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb session"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaconsentrequestsession"},"consentRequestSession")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb access_token"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the",Object(l.b)("br",null),"refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection.",Object(l.b)("br",null),"If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties",Object(l.b)("br",null),"can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care!")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb\xbb id_token"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable",Object(l.b)("br",null),"by anyone that has access to the ID Challenge. Use with care!")))),Object(l.b)("h5",{id:"examples-29"},"Examples"),Object(l.b)("h6",{id:"200-response-21"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'[\n {\n "consent_request": {\n "acr": "string",\n "challenge": "string",\n "client": {\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n },\n "context": {},\n "login_challenge": "string",\n "login_session_id": "string",\n "oidc_context": {\n "acr_values": ["string"],\n "display": "string",\n "id_token_hint_claims": {},\n "login_hint": "string",\n "ui_locales": ["string"]\n },\n "request_url": "string",\n "requested_access_token_audience": ["string"],\n "requested_scope": ["string"],\n "skip": true,\n "subject": "string"\n },\n "grant_access_token_audience": ["string"],\n "grant_scope": ["string"],\n "handled_at": "2019-08-24T14:15:22Z",\n "remember": true,\n "remember_for": 0,\n "session": {\n "access_token": {},\n "id_token": {}\n }\n }\n]\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-31"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /oauth2/auth/sessions/consent?subject=string \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/oauth2/auth/sessions/consent", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/oauth2/auth/sessions/consent?subject=string', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/sessions/consent?subject=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/oauth2/auth/sessions/consent',\n params={\n 'subject': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/oauth2/auth/sessions/consent',\n params: {\n 'subject' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdrevokeConsentSessions"}),Object(l.b)("h3",{id:"revokes-consent-sessions-of-a-subject-for-a-specific-oauth-20-client"},"Revokes Consent Sessions of a Subject for a Specific OAuth 2.0 Client"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"DELETE /oauth2/auth/sessions/consent?subject=string HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint revokes a subject's granted consent sessions for a specific OAuth\n2.0 Client and invalidates all associated OAuth 2.0 Access Tokens."),Object(l.b)("a",{id:"revokes-consent-sessions-of-a-subject-for-a-specific-oauth-2.0-client-parameters"}),Object(l.b)("h4",{id:"parameters-24"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"subject"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The subject (Subject) who's consent sessions should be deleted.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"If set, deletes only those consent sessions by the Subject that have been granted to the specified OAuth 2.0 Client ID")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"all"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"If set to ",Object(l.b)("inlineCode",{parentName:"td"},"?all=true"),", deletes all consent sessions by the Subject that have been granted.")))),Object(l.b)("h4",{id:"responses-32"},"Responses"),Object(l.b)("a",{id:"revokes-consent-sessions-of-a-subject-for-a-specific-oauth-2.0-client-responses"}),Object(l.b)("h5",{id:"overview-32"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"204"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.5"},"No Content")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"400"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.1"},"Bad Request")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-30"},"Examples"),Object(l.b)("h6",{id:"400-response"},"400 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-32"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X DELETE /oauth2/auth/sessions/consent?subject=string \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("DELETE", "/oauth2/auth/sessions/consent", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/oauth2/auth/sessions/consent?subject=string', {\n method: 'DELETE',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/sessions/consent?subject=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("DELETE");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.delete(\n '/oauth2/auth/sessions/consent',\n params={\n 'subject': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.delete '/oauth2/auth/sessions/consent',\n params: {\n 'subject' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdrevokeAuthenticationSession"}),Object(l.b)("h3",{id:"invalidates-all-login-sessions-of-a-certain-user"},"Invalidates All Login Sessions of a Certain User"),Object(l.b)("p",null,"Invalidates a Subject's Authentication Session"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"DELETE /oauth2/auth/sessions/login?subject=string HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint invalidates a subject's authentication session. After revoking the\nauthentication session, the subject has to re-authenticate at ORY Hydra. This\nendpoint does not invalidate any tokens and does not work with OpenID Connect\nFront- or Back-channel logout."),Object(l.b)("a",{id:"invalidates-all-login-sessions-of-a-certain-user\ninvalidates-a-subject's-authentication-session-parameters"}),Object(l.b)("h4",{id:"parameters-25"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"subject"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-33"},"Responses"),Object(l.b)("a",{id:"invalidates-all-login-sessions-of-a-certain-user\ninvalidates-a-subject's-authentication-session-responses"}),Object(l.b)("h5",{id:"overview-33"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"204"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.5"},"No Content")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"400"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.5.1"},"Bad Request")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-31"},"Examples"),Object(l.b)("h6",{id:"400-response-1"},"400 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-33"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X DELETE /oauth2/auth/sessions/login?subject=string \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("DELETE", "/oauth2/auth/sessions/login", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/oauth2/auth/sessions/login?subject=string', {\n method: 'DELETE',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/auth/sessions/login?subject=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("DELETE");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.delete(\n '/oauth2/auth/sessions/login',\n params={\n 'subject': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.delete '/oauth2/auth/sessions/login',\n params: {\n 'subject' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdflushInactiveOAuth2Tokens"}),Object(l.b)("h3",{id:"flush-expired-oauth2-access-tokens"},"Flush Expired OAuth2 Access Tokens"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"POST /oauth2/flush HTTP/1.1\nContent-Type: application/json\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint flushes expired OAuth2 access tokens from the database. You can\nset a time after which no tokens will be not be touched, in case you want to\nkeep recent tokens for auditing. Refresh tokens can not be flushed as they are\ndeleted automatically when performing the refresh flow."),Object(l.b)("h4",{id:"request-body-12"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "notAfter": "2019-08-24T14:15:22Z"\n}\n')),Object(l.b)("a",{id:"flush-expired-oauth2-access-tokens-parameters"}),Object(l.b)("h4",{id:"parameters-26"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaflushinactiveoauth2tokensrequest"},"flushInactiveOAuth2TokensRequest")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-34"},"Responses"),Object(l.b)("a",{id:"flush-expired-oauth2-access-tokens-responses"}),Object(l.b)("h5",{id:"overview-34"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"204"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.5"},"No Content")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-32"},"Examples"),Object(l.b)("h6",{id:"401-response-4"},"401 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-34"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X POST /oauth2/flush \\\n -H 'Content-Type: application/json' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/json"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("POST", "/oauth2/flush", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch');\nconst input = '{\n \"notAfter\": \"2019-08-24T14:15:22Z\"\n}';\nconst headers = {\n 'Content-Type': 'application/json', 'Accept': 'application/json'\n}\n\nfetch('/oauth2/flush', {\n method: 'POST',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/flush");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("POST");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\nr = requests.post(\n '/oauth2/flush',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/json',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.post '/oauth2/flush',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdintrospectOAuth2Token"}),Object(l.b)("h3",{id:"introspect-oauth2-tokens"},"Introspect OAuth2 Tokens"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"POST /oauth2/introspect HTTP/1.1\nContent-Type: application/x-www-form-urlencoded\nAccept: application/json\n\n")),Object(l.b)("p",null,"The introspection endpoint allows to check if a token (both refresh and access)\nis active or not. An active token is neither expired nor revoked. If a token is\nactive, additional information on the token will be included. You can set\nadditional data for a token by setting ",Object(l.b)("inlineCode",{parentName:"p"},"accessTokenExtra")," during the consent\nflow."),Object(l.b)("p",null,"For more information\n",Object(l.b)("a",{parentName:"p",href:"https://www.oauth.com/oauth2-servers/token-introspection-endpoint/"},"read this blog post"),"."),Object(l.b)("h4",{id:"request-body-13"},"Request body"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-yaml"},"token: string\nscope: string\n")),Object(l.b)("a",{id:"introspect-oauth2-tokens-parameters"}),Object(l.b)("h4",{id:"parameters-27"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb token"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"The string value of the token. For access tokens, this")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb scope"),Object(l.b)("td",{parentName:"tr",align:null},"body"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"An optional, space separated list of required scopes. If the access token was not granted one of the")))),Object(l.b)("h5",{id:"detailed-descriptions"},"Detailed descriptions"),Object(l.b)("p",null,Object(l.b)("strong",{parentName:"p"},"\xbb token"),': The string value of the token. For access tokens, this is the\n"access_token" value returned from the token endpoint defined in OAuth 2.0. For\nrefresh tokens, this is the "refresh_token" value returned.'),Object(l.b)("p",null,Object(l.b)("strong",{parentName:"p"},"\xbb scope"),": An optional, space separated list of required scopes. If the access\ntoken was not granted one of the scopes, the result of active will be false."),Object(l.b)("h4",{id:"responses-35"},"Responses"),Object(l.b)("a",{id:"introspect-oauth2-tokens-responses"}),Object(l.b)("h5",{id:"overview-35"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"oAuth2TokenIntrospection"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2tokenintrospection"},"oAuth2TokenIntrospection"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-33"},"Examples"),Object(l.b)("h6",{id:"200-response-22"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "active": true,\n "aud": ["string"],\n "client_id": "string",\n "exp": 0,\n "ext": {},\n "iat": 0,\n "iss": "string",\n "nbf": 0,\n "obfuscated_subject": "string",\n "scope": "string",\n "sub": "string",\n "token_type": "string",\n "token_use": "string",\n "username": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-35"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X POST /oauth2/introspect \\\n -H 'Content-Type: application/x-www-form-urlencoded' \\ -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Content-Type": []string{"application/x-www-form-urlencoded"},\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("POST", "/oauth2/introspect", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch');\nconst input = '{\n \"token\": \"string\",\n \"scope\": \"string\"\n}';\nconst headers = {\n 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'\n}\n\nfetch('/oauth2/introspect', {\n method: 'POST',\n body: input,\n headers\n})\n.then(r => r.json())\n.then((body) => {\n console.log(body)\n})\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/introspect");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("POST");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'application/json'\n}\n\nr = requests.post(\n '/oauth2/introspect',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.post '/oauth2/introspect',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIddeleteOAuth2Token"}),Object(l.b)("h3",{id:"delete-oauth2-access-tokens-from-a-client"},"Delete OAuth2 Access Tokens from a Client"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"DELETE /oauth2/tokens?client_id=string HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint deletes OAuth2 access tokens issued for a client from the database"),Object(l.b)("a",{id:"delete-oauth2-access-tokens-from-a-client-parameters"}),Object(l.b)("h4",{id:"parameters-28"},"Parameters"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Parameter"),Object(l.b)("th",{parentName:"tr",align:null},"In"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client_id"),Object(l.b)("td",{parentName:"tr",align:null},"query"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("h4",{id:"responses-36"},"Responses"),Object(l.b)("a",{id:"delete-oauth2-access-tokens-from-a-client-responses"}),Object(l.b)("h5",{id:"overview-36"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"204"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.5"},"No Content")),Object(l.b)("td",{parentName:"tr",align:null},"Empty responses are sent when, for example, resources are deleted. The HTTP status code for empty responses is typically 201."),Object(l.b)("td",{parentName:"tr",align:null},"None")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"401"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7235#section-3.1"},"Unauthorized")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"500"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.6.1"},"Internal Server Error")),Object(l.b)("td",{parentName:"tr",align:null},"genericError"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemagenericerror"},"genericError"))))),Object(l.b)("h5",{id:"examples-34"},"Examples"),Object(l.b)("h6",{id:"401-response-5"},"401 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-36"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X DELETE /oauth2/tokens?client_id=string \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("DELETE", "/oauth2/tokens", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/oauth2/tokens?client_id=string', {\n method: 'DELETE',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/oauth2/tokens?client_id=string");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("DELETE");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.delete(\n '/oauth2/tokens',\n params={\n 'client_id': 'string'},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.delete '/oauth2/tokens',\n params: {\n 'client_id' => 'string'}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("a",{id:"opIdgetVersion"}),Object(l.b)("h3",{id:"get-service-version"},"Get Service Version"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre"},"GET /version HTTP/1.1\nAccept: application/json\n\n")),Object(l.b)("p",null,"This endpoint returns the service version typically notated using semantic\nversioning."),Object(l.b)("p",null,"If the service supports TLS Edge Termination, this endpoint does not require the\n",Object(l.b)("inlineCode",{parentName:"p"},"X-Forwarded-Proto")," header to be set."),Object(l.b)("h4",{id:"responses-37"},"Responses"),Object(l.b)("a",{id:"get-service-version-responses"}),Object(l.b)("h5",{id:"overview-37"},"Overview"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Status"),Object(l.b)("th",{parentName:"tr",align:null},"Meaning"),Object(l.b)("th",{parentName:"tr",align:null},"Description"),Object(l.b)("th",{parentName:"tr",align:null},"Schema"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"200"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"https://tools.ietf.org/html/rfc7231#section-6.3.1"},"OK")),Object(l.b)("td",{parentName:"tr",align:null},"version"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaversion"},"version"))))),Object(l.b)("h5",{id:"examples-35"},"Examples"),Object(l.b)("h6",{id:"200-response-23"},"200 response"),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "version": "string"\n}\n')),Object(l.b)("aside",{class:"success"},"This operation does not require authentication"),Object(l.b)("h4",{id:"code-samples-37"},"Code samples"),Object(l.b)(b.a,{groupId:"code-samples",defaultValue:"shell",values:[{label:"Shell",value:"shell"},{label:"Go",value:"go"},{label:"Node",value:"node"},{label:"Java",value:"java"},{label:"Python",value:"python"},{label:"Ruby",value:"ruby"}],mdxType:"Tabs"},Object(l.b)(i.a,{value:"shell",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-shell"},"curl -X GET /version \\\n -H 'Accept: application/json'\n"))),Object(l.b)(i.a,{value:"go",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-go"},'package main\n\nimport (\n "bytes"\n "net/http"\n)\n\nfunc main() {\n headers := map[string][]string{\n "Accept": []string{"application/json"},\n }\n\n var body []byte\n // body = ...\n\n req, err := http.NewRequest("GET", "/version", bytes.NewBuffer(body))\n req.Header = headers\n\n client := &http.Client{}\n resp, err := client.Do(req)\n // ...\n}\n'))),Object(l.b)(i.a,{value:"node",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-javascript"},"const fetch = require('node-fetch')\n\nconst headers = {\n Accept: 'application/json'\n}\n\nfetch('/version', {\n method: 'GET',\n headers\n})\n .then((r) => r.json())\n .then((body) => {\n console.log(body)\n })\n"))),Object(l.b)(i.a,{value:"java",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-java"},'// This sample needs improvement.\nURL obj = new URL("/version");\n\nHttpURLConnection con = (HttpURLConnection) obj.openConnection();\ncon.setRequestMethod("GET");\n\nint responseCode = con.getResponseCode();\n\nBufferedReader in = new BufferedReader(\n new InputStreamReader(con.getInputStream())\n);\n\nString inputLine;\nStringBuffer response = new StringBuffer();\nwhile ((inputLine = in.readLine()) != null) {\n response.append(inputLine);\n}\nin.close();\n\nSystem.out.println(response.toString());\n'))),Object(l.b)(i.a,{value:"python",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-python"},"import requests\n\nheaders = {\n 'Accept': 'application/json'\n}\n\nr = requests.get(\n '/version',\n params={},\n headers = headers)\n\nprint r.json()\n"))),Object(l.b)(i.a,{value:"ruby",mdxType:"TabItem"},Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-ruby"},"require 'rest-client'\nrequire 'json'\n\nheaders = {\n 'Accept' => 'application/json'\n}\n\nresult = RestClient.get '/version',\n params: {}, headers: headers\n\np JSON.parse(result)\n")))),Object(l.b)("h2",{id:"schemas"},"Schemas"),Object(l.b)("a",{id:"tocScontainerwaitokbodyerror"}),Object(l.b)("h4",{id:"containerwaitokbodyerror"},"ContainerWaitOKBodyError"),Object(l.b)("a",{id:"schemacontainerwaitokbodyerror"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "Message": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"ContainerWaitOKBodyError container waiting error, if any")),Object(l.b)("h4",{id:"properties"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Message"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Details of an error")))),Object(l.b)("a",{id:"tocSjsonrawmessage"}),Object(l.b)("h4",{id:"jsonrawmessage"},"JSONRawMessage"),Object(l.b)("a",{id:"schemajsonrawmessage"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},"{}\n")),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"JSONRawMessage represents a json.RawMessage that works well with JSON, SQL, and\nSwagger.")),Object(l.b)("h4",{id:"properties-1"},"Properties"),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"None")),Object(l.b)("a",{id:"tocSjsonwebkey"}),Object(l.b)("h4",{id:"jsonwebkey"},"JSONWebKey"),Object(l.b)("a",{id:"schemajsonwebkey"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},'It is important that this model object is named JSONWebKey for "swagger\ngenerate spec" to generate only on definition of a JSONWebKey.')),Object(l.b)("h4",{id:"properties-2"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'The "alg" (algorithm) parameter identifies the algorithm intended for',Object(l.b)("br",null),"use with the key. The values used should either be registered in the",Object(l.b)("br",null),'IANA "JSON Web Signature and Encryption Algorithms" registry',Object(l.b)("br",null),"established by ","[JWA]"," or be a value that contains a Collision-",Object(l.b)("br",null),"Resistant Name.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"crv"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"d"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"dp"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"dq"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"e"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"k"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"kid"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'The "kid" (key ID) parameter is used to match a specific key. This',Object(l.b)("br",null),"is used, for instance, to choose among a set of keys within a JWK Set",Object(l.b)("br",null),'during key rollover. The structure of the "kid" value is',Object(l.b)("br",null),'unspecified. When "kid" values are used within a JWK Set, different',Object(l.b)("br",null),'keys within the JWK Set SHOULD use distinct "kid" values. (One',Object(l.b)("br",null),'example in which different keys might use the same "kid" value is if',Object(l.b)("br",null),'they have different "kty" (key type) values but are considered to be',Object(l.b)("br",null),'equivalent alternatives by the application using them.) The "kid"',Object(l.b)("br",null),"value is a case-sensitive string.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"kty"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'The "kty" (key type) parameter identifies the cryptographic algorithm',Object(l.b)("br",null),'family used with the key, such as "RSA" or "EC". "kty" values should',Object(l.b)("br",null),'either be registered in the IANA "JSON Web Key Types" registry',Object(l.b)("br",null),"established by ","[JWA]"," or be a value that contains a Collision-",Object(l.b)("br",null),'Resistant Name. The "kty" value is a case-sensitive string.')),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"n"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"p"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"q"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"qi"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"use"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'Use ("public key use") identifies the intended use of',Object(l.b)("br",null),'the public key. The "use" parameter is employed to indicate whether',Object(l.b)("br",null),"a public key is used for encrypting data or verifying the signature",Object(l.b)("br",null),'on data. Values are commonly "sig" (signature) or "enc" (encryption).')),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"x"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"x5c"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'The "x5c" (X.509 certificate chain) parameter contains a chain of one',Object(l.b)("br",null),"or more PKIX certificates ","[RFC5280]",". The certificate chain is",Object(l.b)("br",null),"represented as a JSON array of certificate value strings. Each",Object(l.b)("br",null),"string in the array is a base64-encoded (Section 4 of ","[RFC4648]"," --",Object(l.b)("br",null),"not base64url-encoded) DER ","[ITU.X690.1994]"," PKIX certificate value.",Object(l.b)("br",null),"The PKIX certificate containing the key value MUST be the first",Object(l.b)("br",null),"certificate.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"y"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("a",{id:"tocSjsonwebkeyset"}),Object(l.b)("h4",{id:"jsonwebkeyset"},"JSONWebKeySet"),Object(l.b)("a",{id:"schemajsonwebkeyset"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "keys": [\n {\n "alg": "RS256",\n "crv": "P-256",\n "d": "T_N8I-6He3M8a7X1vWt6TGIx4xB_GP3Mb4SsZSA4v-orvJzzRiQhLlRR81naWYxfQAYt5isDI6_C2L9bdWo4FFPjGQFvNoRX-_sBJyBI_rl-TBgsZYoUlAj3J92WmY2inbA-PwyJfsaIIDceYBC-eX-xiCu6qMqkZi3MwQAFL6bMdPEM0z4JBcwFT3VdiWAIRUuACWQwrXMq672x7fMuaIaHi7XDGgt1ith23CLfaREmJku9PQcchbt_uEY-hqrFY6ntTtS4paWWQj86xLL94S-Tf6v6xkL918PfLSOTq6XCzxvlFwzBJqApnAhbwqLjpPhgUG04EDRrqrSBc5Y1BLevn6Ip5h1AhessBp3wLkQgz_roeckt-ybvzKTjESMuagnpqLvOT7Y9veIug2MwPJZI2VjczRc1vzMs25XrFQ8DpUy-bNdp89TmvAXwctUMiJdgHloJw23Cv03gIUAkDnsTqZmkpbIf-crpgNKFmQP_EDKoe8p_PXZZgfbRri3NoEVGP7Mk6yEu8LjJhClhZaBNjuWw2-KlBfOA3g79mhfBnkInee5KO9mGR50qPk1V-MorUYNTFMZIm0kFE6eYVWFBwJHLKYhHU34DoiK1VP-svZpC2uAMFNA_UJEwM9CQ2b8qe4-5e9aywMvwcuArRkAB5mBIfOaOJao3mfukKAE",\n "dp": "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0",\n "dq": "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk",\n "e": "AQAB",\n "k": "GawgguFyGrWKav7AX4VKUg",\n "kid": "1603dfe0af8f4596",\n "kty": "RSA",\n "n": "vTqrxUyQPl_20aqf5kXHwDZrel-KovIp8s7ewJod2EXHl8tWlRB3_Rem34KwBfqlKQGp1nqah-51H4Jzruqe0cFP58hPEIt6WqrvnmJCXxnNuIB53iX_uUUXXHDHBeaPCSRoNJzNysjoJ30TIUsKBiirhBa7f235PXbKiHducLevV6PcKxJ5cY8zO286qJLBWSPm-OIevwqsIsSIH44Qtm9sioFikhkbLwoqwWORGAY0nl6XvVOlhADdLjBSqSAeT1FPuCDCnXwzCDR8N9IFB_IjdStFkC-rVt2K5BYfPd0c3yFp_vHR15eRd0zJ8XQ7woBC8Vnsac6Et1pKS59pX6256DPWu8UDdEOolKAPgcd_g2NpA76cAaF_jcT80j9KrEzw8Tv0nJBGesuCjPNjGs_KzdkWTUXt23Hn9QJsdc1MZuaW0iqXBepHYfYoqNelzVte117t4BwVp0kUM6we0IqyXClaZgOI8S-WDBw2_Ovdm8e5NmhYAblEVoygcX8Y46oH6bKiaCQfKCFDMcRgChme7AoE1yZZYsPbaG_3IjPrC4LBMHQw8rM9dWjJ8ImjicvZ1pAm0dx-KHCP3y5PVKrxBDf1zSOsBRkOSjB8TPODnJMz6-jd5hTtZxpZPwPoIdCanTZ3ZD6uRBpTmDwtpRGm63UQs1m5FWPwb0T2IF0",\n "p": "6NbkXwDWUhi-eR55Cgbf27FkQDDWIamOaDr0rj1q0f1fFEz1W5A_09YvG09Fiv1AO2-D8Rl8gS1Vkz2i0zCSqnyy8A025XOcRviOMK7nIxE4OH_PEsko8dtIrb3TmE2hUXvCkmzw9EsTF1LQBOGC6iusLTXepIC1x9ukCKFZQvdgtEObQ5kzd9Nhq-cdqmSeMVLoxPLd1blviVT9Vm8-y12CtYpeJHOaIDtVPLlBhJiBoPKWg3vxSm4XxIliNOefqegIlsmTIa3MpS6WWlCK3yHhat0Q-rRxDxdyiVdG_wzJvp0Iw_2wms7pe-PgNPYvUWH9JphWP5K38YqEBiJFXQ",\n "q": "0A1FmpOWR91_RAWpqreWSavNaZb9nXeKiBo0DQGBz32DbqKqQ8S4aBJmbRhJcctjCLjain-ivut477tAUMmzJwVJDDq2MZFwC9Q-4VYZmFU4HJityQuSzHYe64RjN-E_NQ02TWhG3QGW6roq6c57c99rrUsETwJJiwS8M5p15Miuz53DaOjv-uqqFAFfywN5WkxHbraBcjHtMiQuyQbQqkCFh-oanHkwYNeytsNhTu2mQmwR5DR2roZ2nPiFjC6nsdk-A7E3S3wMzYYFw7jvbWWoYWo9vB40_MY2Y0FYQSqcDzcBIcq_0tnnasf3VW4Fdx6m80RzOb2Fsnln7vKXAQ",\n "qi": "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU",\n "use": "sig",\n "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",\n "x5c": ["string"],\n "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0"\n }\n ]\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},'It is important that this model object is named JSONWebKeySet for "swagger\ngenerate spec" to generate only on definition of a JSONWebKeySet. Since one with\nthe same name is previously defined as client.Client.JSONWebKeys and this one is\nlast, this one will be effectively written in the swagger spec.')),Object(l.b)("h4",{id:"properties-3"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"keys"),Object(l.b)("td",{parentName:"tr",align:null},"[",Object(l.b)("a",{parentName:"td",href:"#schemajsonwebkey"},"JSONWebKey"),"]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'The value of the "keys" parameter is an array of JWK values. By',Object(l.b)("br",null),"default, the order of the JWK values within the array does not imply",Object(l.b)("br",null),"an order of preference among them, although applications of JWK Sets",Object(l.b)("br",null),"can choose to assign a meaning to the order for their purposes, if",Object(l.b)("br",null),"desired.")))),Object(l.b)("a",{id:"tocSjosejsonwebkeyset"}),Object(l.b)("h4",{id:"josejsonwebkeyset"},"JoseJSONWebKeySet"),Object(l.b)("a",{id:"schemajosejsonwebkeyset"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},"{}\n")),Object(l.b)("h4",{id:"properties-4"},"Properties"),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"None")),Object(l.b)("a",{id:"tocSnulltime"}),Object(l.b)("h4",{id:"nulltime"},"NullTime"),Object(l.b)("a",{id:"schemanulltime"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'"2019-08-24T14:15:22Z"\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"NullTime implements sql.NullTime functionality.")),Object(l.b)("h4",{id:"properties-5"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"NullTime implements sql.NullTime functionality."),Object(l.b)("td",{parentName:"tr",align:null},"string(date-time)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("a",{id:"tocSpluginconfig"}),Object(l.b)("h4",{id:"pluginconfig"},"PluginConfig"),Object(l.b)("a",{id:"schemapluginconfig"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "Args": {\n "Description": "string",\n "Name": "string",\n "Settable": ["string"],\n "Value": ["string"]\n },\n "Description": "string",\n "DockerVersion": "string",\n "Documentation": "string",\n "Entrypoint": ["string"],\n "Env": [\n {\n "Description": "string",\n "Name": "string",\n "Settable": ["string"],\n "Value": "string"\n }\n ],\n "Interface": {\n "ProtocolScheme": "string",\n "Socket": "string",\n "Types": [\n {\n "Capability": "string",\n "Prefix": "string",\n "Version": "string"\n }\n ]\n },\n "IpcHost": true,\n "Linux": {\n "AllowAllDevices": true,\n "Capabilities": ["string"],\n "Devices": [\n {\n "Description": "string",\n "Name": "string",\n "Path": "string",\n "Settable": ["string"]\n }\n ]\n },\n "Mounts": [\n {\n "Description": "string",\n "Destination": "string",\n "Name": "string",\n "Options": ["string"],\n "Settable": ["string"],\n "Source": "string",\n "Type": "string"\n }\n ],\n "Network": {\n "Type": "string"\n },\n "PidHost": true,\n "PropagatedMount": "string",\n "User": {\n "GID": 0,\n "UID": 0\n },\n "WorkDir": "string",\n "rootfs": {\n "diff_ids": ["string"],\n "type": "string"\n }\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginConfig The config of a plugin.")),Object(l.b)("h4",{id:"properties-6"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Args"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemapluginconfigargs"},"PluginConfigArgs")),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"PluginConfigArgs plugin config args")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Description"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"description")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"DockerVersion"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Docker Version used to create the plugin")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Documentation"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"documentation")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Entrypoint"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"entrypoint")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Env"),Object(l.b)("td",{parentName:"tr",align:null},"[",Object(l.b)("a",{parentName:"td",href:"#schemapluginenv"},"PluginEnv"),"]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"env")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Interface"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemapluginconfiginterface"},"PluginConfigInterface")),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"PluginConfigInterface The interface between Docker and the plugin")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"IpcHost"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ipc host")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Linux"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemapluginconfiglinux"},"PluginConfigLinux")),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"PluginConfigLinux plugin config linux")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Mounts"),Object(l.b)("td",{parentName:"tr",align:null},"[",Object(l.b)("a",{parentName:"td",href:"#schemapluginmount"},"PluginMount"),"]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"mounts")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Network"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemapluginconfignetwork"},"PluginConfigNetwork")),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"PluginConfigNetwork plugin config network")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"PidHost"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"pid host")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"PropagatedMount"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"propagated mount")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"User"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemapluginconfiguser"},"PluginConfigUser")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"PluginConfigUser plugin config user")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"WorkDir"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"work dir")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"rootfs"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemapluginconfigrootfs"},"PluginConfigRootfs")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"PluginConfigRootfs plugin config rootfs")))),Object(l.b)("a",{id:"tocSpluginconfigargs"}),Object(l.b)("h4",{id:"pluginconfigargs"},"PluginConfigArgs"),Object(l.b)("a",{id:"schemapluginconfigargs"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "Description": "string",\n "Name": "string",\n "Settable": ["string"],\n "Value": ["string"]\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginConfigArgs plugin config args")),Object(l.b)("h4",{id:"properties-7"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Description"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"description")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"name")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Settable"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"settable")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Value"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"value")))),Object(l.b)("a",{id:"tocSpluginconfiginterface"}),Object(l.b)("h4",{id:"pluginconfiginterface"},"PluginConfigInterface"),Object(l.b)("a",{id:"schemapluginconfiginterface"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "ProtocolScheme": "string",\n "Socket": "string",\n "Types": [\n {\n "Capability": "string",\n "Prefix": "string",\n "Version": "string"\n }\n ]\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginConfigInterface The interface between Docker and the plugin")),Object(l.b)("h4",{id:"properties-8"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"ProtocolScheme"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Protocol to use for clients connecting to the plugin.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Socket"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"socket")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Types"),Object(l.b)("td",{parentName:"tr",align:null},"[",Object(l.b)("a",{parentName:"td",href:"#schemaplugininterfacetype"},"PluginInterfaceType"),"]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"types")))),Object(l.b)("a",{id:"tocSpluginconfiglinux"}),Object(l.b)("h4",{id:"pluginconfiglinux"},"PluginConfigLinux"),Object(l.b)("a",{id:"schemapluginconfiglinux"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "AllowAllDevices": true,\n "Capabilities": ["string"],\n "Devices": [\n {\n "Description": "string",\n "Name": "string",\n "Path": "string",\n "Settable": ["string"]\n }\n ]\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginConfigLinux plugin config linux")),Object(l.b)("h4",{id:"properties-9"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"AllowAllDevices"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"allow all devices")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Capabilities"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"capabilities")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Devices"),Object(l.b)("td",{parentName:"tr",align:null},"[",Object(l.b)("a",{parentName:"td",href:"#schemaplugindevice"},"PluginDevice"),"]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"devices")))),Object(l.b)("a",{id:"tocSpluginconfignetwork"}),Object(l.b)("h4",{id:"pluginconfignetwork"},"PluginConfigNetwork"),Object(l.b)("a",{id:"schemapluginconfignetwork"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "Type": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginConfigNetwork plugin config network")),Object(l.b)("h4",{id:"properties-10"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Type"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"type")))),Object(l.b)("a",{id:"tocSpluginconfigrootfs"}),Object(l.b)("h4",{id:"pluginconfigrootfs"},"PluginConfigRootfs"),Object(l.b)("a",{id:"schemapluginconfigrootfs"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "diff_ids": ["string"],\n "type": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginConfigRootfs plugin config rootfs")),Object(l.b)("h4",{id:"properties-11"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"diff_ids"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"diff ids")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"type"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"type")))),Object(l.b)("a",{id:"tocSpluginconfiguser"}),Object(l.b)("h4",{id:"pluginconfiguser"},"PluginConfigUser"),Object(l.b)("a",{id:"schemapluginconfiguser"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "GID": 0,\n "UID": 0\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginConfigUser plugin config user")),Object(l.b)("h4",{id:"properties-12"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"GID"),Object(l.b)("td",{parentName:"tr",align:null},"integer(uint32)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"g ID")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"UID"),Object(l.b)("td",{parentName:"tr",align:null},"integer(uint32)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"UID")))),Object(l.b)("a",{id:"tocSplugindevice"}),Object(l.b)("h4",{id:"plugindevice"},"PluginDevice"),Object(l.b)("a",{id:"schemaplugindevice"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "Description": "string",\n "Name": "string",\n "Path": "string",\n "Settable": ["string"]\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginDevice plugin device")),Object(l.b)("h4",{id:"properties-13"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Description"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"description")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"name")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Path"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"path")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Settable"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"settable")))),Object(l.b)("a",{id:"tocSpluginenv"}),Object(l.b)("h4",{id:"pluginenv"},"PluginEnv"),Object(l.b)("a",{id:"schemapluginenv"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "Description": "string",\n "Name": "string",\n "Settable": ["string"],\n "Value": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginEnv plugin env")),Object(l.b)("h4",{id:"properties-14"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Description"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"description")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"name")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Settable"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"settable")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Value"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"value")))),Object(l.b)("a",{id:"tocSplugininterfacetype"}),Object(l.b)("h4",{id:"plugininterfacetype"},"PluginInterfaceType"),Object(l.b)("a",{id:"schemaplugininterfacetype"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "Capability": "string",\n "Prefix": "string",\n "Version": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginInterfaceType plugin interface type")),Object(l.b)("h4",{id:"properties-15"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Capability"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"capability")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Prefix"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"prefix")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Version"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"version")))),Object(l.b)("a",{id:"tocSpluginmount"}),Object(l.b)("h4",{id:"pluginmount"},"PluginMount"),Object(l.b)("a",{id:"schemapluginmount"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "Description": "string",\n "Destination": "string",\n "Name": "string",\n "Options": ["string"],\n "Settable": ["string"],\n "Source": "string",\n "Type": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginMount plugin mount")),Object(l.b)("h4",{id:"properties-16"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Description"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"description")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Destination"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"destination")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"name")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Options"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"options")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Settable"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"settable")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Source"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"source")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Type"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"type")))),Object(l.b)("a",{id:"tocSpluginsettings"}),Object(l.b)("h4",{id:"pluginsettings"},"PluginSettings"),Object(l.b)("a",{id:"schemapluginsettings"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "Args": ["string"],\n "Devices": [\n {\n "Description": "string",\n "Name": "string",\n "Path": "string",\n "Settable": ["string"]\n }\n ],\n "Env": ["string"],\n "Mounts": [\n {\n "Description": "string",\n "Destination": "string",\n "Name": "string",\n "Options": ["string"],\n "Settable": ["string"],\n "Source": "string",\n "Type": "string"\n }\n ]\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"PluginSettings Settings that can be modified by users.")),Object(l.b)("h4",{id:"properties-17"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Args"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"args")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Devices"),Object(l.b)("td",{parentName:"tr",align:null},"[",Object(l.b)("a",{parentName:"td",href:"#schemaplugindevice"},"PluginDevice"),"]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"devices")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Env"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"env")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Mounts"),Object(l.b)("td",{parentName:"tr",align:null},"[",Object(l.b)("a",{parentName:"td",href:"#schemapluginmount"},"PluginMount"),"]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"mounts")))),Object(l.b)("a",{id:"tocSpreviousconsentsession"}),Object(l.b)("h4",{id:"previousconsentsession"},"PreviousConsentSession"),Object(l.b)("a",{id:"schemapreviousconsentsession"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "consent_request": {\n "acr": "string",\n "challenge": "string",\n "client": {\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n },\n "context": {},\n "login_challenge": "string",\n "login_session_id": "string",\n "oidc_context": {\n "acr_values": ["string"],\n "display": "string",\n "id_token_hint_claims": {},\n "login_hint": "string",\n "ui_locales": ["string"]\n },\n "request_url": "string",\n "requested_access_token_audience": ["string"],\n "requested_scope": ["string"],\n "skip": true,\n "subject": "string"\n },\n "grant_access_token_audience": ["string"],\n "grant_scope": ["string"],\n "handled_at": "2019-08-24T14:15:22Z",\n "remember": true,\n "remember_for": 0,\n "session": {\n "access_token": {},\n "id_token": {}\n }\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"The response used to return used consent requests same as HandledLoginRequest,\njust with consent_request exposed as json")),Object(l.b)("h4",{id:"properties-18"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"consent_request"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaconsentrequest"},"consentRequest")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"grant_access_token_audience"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"grant_scope"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"handled_at"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemanulltime"},"NullTime")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"remember"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same",Object(l.b)("br",null),"client asks the same user for the same, or a subset of, scope.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"remember_for"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RememberFor sets how long the consent authorization should be remembered for in seconds. If set to ",Object(l.b)("inlineCode",{parentName:"td"},"0"),", the",Object(l.b)("br",null),"authorization will be remembered indefinitely.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"session"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaconsentrequestsession"},"consentRequestSession")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("a",{id:"tocSstringslicepipedelimiter"}),Object(l.b)("h4",{id:"stringslicepipedelimiter"},"StringSlicePipeDelimiter"),Object(l.b)("a",{id:"schemastringslicepipedelimiter"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'["string"]\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"StringSlicePipeDelimiter de/encodes the string slice to/from a SQL string.")),Object(l.b)("h4",{id:"properties-19"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"StringSlicePipeDelimiter de/encodes the string slice to/from a SQL string."),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("a",{id:"tocSvolume"}),Object(l.b)("h4",{id:"volume"},"Volume"),Object(l.b)("a",{id:"schemavolume"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "CreatedAt": "string",\n "Driver": "string",\n "Labels": {\n "property1": "string",\n "property2": "string"\n },\n "Mountpoint": "string",\n "Name": "string",\n "Options": {\n "property1": "string",\n "property2": "string"\n },\n "Scope": "string",\n "Status": {},\n "UsageData": {\n "RefCount": 0,\n "Size": 0\n }\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"Volume volume")),Object(l.b)("h4",{id:"properties-20"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"CreatedAt"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Date/Time the volume was created.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Driver"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Name of the volume driver used by the volume.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Labels"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"User-defined key/value metadata.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb ",Object(l.b)("strong",{parentName:"td"},"additionalProperties")),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Mountpoint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Mount path of the volume on the host.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Name of the volume.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Options"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"The driver specific options used when creating the volume.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb ",Object(l.b)("strong",{parentName:"td"},"additionalProperties")),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Scope"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"The level at which the volume exists. Either ",Object(l.b)("inlineCode",{parentName:"td"},"global")," for cluster-wide, or ",Object(l.b)("inlineCode",{parentName:"td"},"local")," for machine level.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Status"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Low-level details about the volume, provided by the volume driver.",Object(l.b)("br",null),"Details are returned as a map with key/value pairs:",Object(l.b)("br",null),Object(l.b)("inlineCode",{parentName:"td"},'{"key":"value","key2":"value2"}'),".",Object(l.b)("br",null),Object(l.b)("br",null),"The ",Object(l.b)("inlineCode",{parentName:"td"},"Status")," field is optional, and is omitted if the volume driver",Object(l.b)("br",null),"does not support this feature.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"UsageData"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemavolumeusagedata"},"VolumeUsageData")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"VolumeUsageData Usage details about the volume. This information is used by the",Object(l.b)("br",null),Object(l.b)("inlineCode",{parentName:"td"},"GET /system/df")," endpoint, and omitted in other endpoints.")))),Object(l.b)("a",{id:"tocSvolumeusagedata"}),Object(l.b)("h4",{id:"volumeusagedata"},"VolumeUsageData"),Object(l.b)("a",{id:"schemavolumeusagedata"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "RefCount": 0,\n "Size": 0\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"VolumeUsageData Usage details about the volume. This information is used by the\n",Object(l.b)("inlineCode",{parentName:"em"},"GET /system/df")," endpoint, and omitted in other endpoints.")),Object(l.b)("h4",{id:"properties-21"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"RefCount"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"The number of containers referencing this volume. This field",Object(l.b)("br",null),"is set to ",Object(l.b)("inlineCode",{parentName:"td"},"-1")," if the reference-count is not available.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"Size"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Amount of disk space used by the volume (in bytes). This information",Object(l.b)("br",null),"is only available for volumes created with the ",Object(l.b)("inlineCode",{parentName:"td"},'"local"')," volume",Object(l.b)("br",null),"driver. For volumes created with other volume drivers, this field",Object(l.b)("br",null),"is set to ",Object(l.b)("inlineCode",{parentName:"td"},"-1"),' ("not available")')))),Object(l.b)("a",{id:"tocSacceptconsentrequest"}),Object(l.b)("h4",{id:"acceptconsentrequest"},"acceptConsentRequest"),Object(l.b)("a",{id:"schemaacceptconsentrequest"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "grant_access_token_audience": ["string"],\n "grant_scope": ["string"],\n "handled_at": "2019-08-24T14:15:22Z",\n "remember": true,\n "remember_for": 0,\n "session": {\n "access_token": {},\n "id_token": {}\n }\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"The request payload used to accept a consent request.")),Object(l.b)("h4",{id:"properties-22"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"grant_access_token_audience"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"grant_scope"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"handled_at"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemanulltime"},"NullTime")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"remember"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same",Object(l.b)("br",null),"client asks the same user for the same, or a subset of, scope.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"remember_for"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RememberFor sets how long the consent authorization should be remembered for in seconds. If set to ",Object(l.b)("inlineCode",{parentName:"td"},"0"),", the",Object(l.b)("br",null),"authorization will be remembered indefinitely.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"session"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaconsentrequestsession"},"consentRequestSession")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("a",{id:"tocSacceptloginrequest"}),Object(l.b)("h4",{id:"acceptloginrequest"},"acceptLoginRequest"),Object(l.b)("a",{id:"schemaacceptloginrequest"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "acr": "string",\n "context": {},\n "force_subject_identifier": "string",\n "remember": true,\n "remember_for": 0,\n "subject": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"HandledLoginRequest is the request payload used to accept a login request.")),Object(l.b)("h4",{id:"properties-23"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"acr"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ACR sets the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it",Object(l.b)("br",null),"to express that, for example, a user authenticated using two factor authentication.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"context"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonrawmessage"},"JSONRawMessage")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"force_subject_identifier"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'ForceSubjectIdentifier forces the "pairwise" user ID of the end-user that authenticated. The "pairwise" user ID refers to the',Object(l.b)("br",null),"(Pairwise Identifier Algorithm)","[http://openid.net/specs/openid-connect-core-1_0.html#PairwiseAlg]"," of the OpenID",Object(l.b)("br",null),'Connect specification. It allows you to set an obfuscated subject ("user") identifier that is unique to the client.',Object(l.b)("br",null),Object(l.b)("br",null),"Please note that this changes the user ID on endpoint /userinfo and sub claim of the ID Token. It does not change the",Object(l.b)("br",null),"sub claim in the OAuth 2.0 Introspection.",Object(l.b)("br",null),Object(l.b)("br",null),"Per default, ORY Hydra handles this value with its own algorithm. In case you want to set this yourself",Object(l.b)("br",null),"you can use this field. Please note that setting this field has no effect if ",Object(l.b)("inlineCode",{parentName:"td"},"pairwise")," is not configured in",Object(l.b)("br",null),"ORY Hydra or the OAuth 2.0 Client does not expect a pairwise identifier (set via ",Object(l.b)("inlineCode",{parentName:"td"},"subject_type")," key in the client's",Object(l.b)("br",null),"configuration).",Object(l.b)("br",null),Object(l.b)("br",null),"Please also be aware that ORY Hydra is unable to properly compute this value during authentication. This implies",Object(l.b)("br",null),"that you have to compute this value on every authentication process (probably depending on the client ID or some",Object(l.b)("br",null),"other unique value).",Object(l.b)("br",null),Object(l.b)("br",null),"If you fail to compute the proper value, then authentication processes which have id_token_hint set might fail.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"remember"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Remember, if set to true, tells ORY Hydra to remember this user by telling the user agent (browser) to store",Object(l.b)("br",null),"a cookie with authentication data. If the same user performs another OAuth 2.0 Authorization Request, he/she",Object(l.b)("br",null),"will not be asked to log in again.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"remember_for"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RememberFor sets how long the authentication should be remembered for in seconds. If set to ",Object(l.b)("inlineCode",{parentName:"td"},"0"),", the",Object(l.b)("br",null),"authorization will be remembered for the duration of the browser session (using a session cookie).")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"subject"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Subject is the user ID of the end-user that authenticated.")))),Object(l.b)("a",{id:"tocScompletedrequest"}),Object(l.b)("h4",{id:"completedrequest"},"completedRequest"),Object(l.b)("a",{id:"schemacompletedrequest"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "redirect_to": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"The response payload sent when accepting or rejecting a login or consent\nrequest.")),Object(l.b)("h4",{id:"properties-24"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"redirect_to"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RedirectURL is the URL which you should redirect the user to once the authentication process is completed.")))),Object(l.b)("a",{id:"tocSconsentrequest"}),Object(l.b)("h4",{id:"consentrequest"},"consentRequest"),Object(l.b)("a",{id:"schemaconsentrequest"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "acr": "string",\n "challenge": "string",\n "client": {\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n },\n "context": {},\n "login_challenge": "string",\n "login_session_id": "string",\n "oidc_context": {\n "acr_values": ["string"],\n "display": "string",\n "id_token_hint_claims": {},\n "login_hint": "string",\n "ui_locales": ["string"]\n },\n "request_url": "string",\n "requested_access_token_audience": ["string"],\n "requested_scope": ["string"],\n "skip": true,\n "subject": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"Contains information on an ongoing consent request.")),Object(l.b)("h4",{id:"properties-25"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"acr"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ACR represents the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it",Object(l.b)("br",null),"to express that, for example, a user authenticated using two factor authentication.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"challenge"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'ID is the identifier ("authorization challenge") of the consent authorization request. It is used to',Object(l.b)("br",null),"identify the session.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"context"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonrawmessage"},"JSONRawMessage")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"login_challenge"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"LoginChallenge is the login challenge this consent challenge belongs to. It can be used to associate",Object(l.b)("br",null),"a login and consent request in the login & consent app.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"login_session_id"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"LoginSessionID is the login session ID. If the user-agent reuses a login session (via cookie / remember flag)",Object(l.b)("br",null),"this ID will remain the same. If the user-agent did not have an existing authentication session (e.g. remember is false)",Object(l.b)("br",null),'this will be a new random value. This value is used as the "sid" parameter in the ID Token and in OIDC Front-/Back-',Object(l.b)("br",null),"channel logout. It's value can generally be used to associate consecutive login requests by a certain user.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"oidc_context"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaopenidconnectcontext"},"openIDConnectContext")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"request_url"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which",Object(l.b)("br",null),"initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but",Object(l.b)("br",null),"might come in handy if you want to deal with additional request parameters.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"requested_access_token_audience"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"requested_scope"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"skip"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Skip, if true, implies that the client has requested the same scopes from the same user previously.",Object(l.b)("br",null),"If true, you must not ask the user to grant the requested scopes. You must however either allow or deny the",Object(l.b)("br",null),"consent request using the usual API call.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"subject"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope",Object(l.b)("br",null),"requested by the OAuth 2.0 client.")))),Object(l.b)("a",{id:"tocSconsentrequestsession"}),Object(l.b)("h4",{id:"consentrequestsession"},"consentRequestSession"),Object(l.b)("a",{id:"schemaconsentrequestsession"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "access_token": {},\n "id_token": {}\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"Used to pass session data to a consent request.")),Object(l.b)("h4",{id:"properties-26"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"access_token"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the",Object(l.b)("br",null),"refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection.",Object(l.b)("br",null),"If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties",Object(l.b)("br",null),"can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care!")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"id_token"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable",Object(l.b)("br",null),"by anyone that has access to the ID Challenge. Use with care!")))),Object(l.b)("a",{id:"tocSflushinactiveoauth2tokensrequest"}),Object(l.b)("h4",{id:"flushinactiveoauth2tokensrequest"},"flushInactiveOAuth2TokensRequest"),Object(l.b)("a",{id:"schemaflushinactiveoauth2tokensrequest"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "notAfter": "2019-08-24T14:15:22Z"\n}\n')),Object(l.b)("h4",{id:"properties-27"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"notAfter"),Object(l.b)("td",{parentName:"tr",align:null},"string(date-time)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"NotAfter sets after which point tokens should not be flushed. This is useful when you want to keep a history",Object(l.b)("br",null),"of recently issued tokens for auditing.")))),Object(l.b)("a",{id:"tocSgenericerror"}),Object(l.b)("h4",{id:"genericerror"},"genericError"),Object(l.b)("a",{id:"schemagenericerror"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "debug": "The database adapter was unable to find the element",\n "error": "The requested resource could not be found",\n "error_description": "Object with ID 12345 does not exist",\n "status_code": 404\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"Error response")),Object(l.b)("h4",{id:"properties-28"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"debug"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Debug contains debug information. This is usually not available and has to be enabled.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"error"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Name is the error name.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"error_description"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Description contains further information on the nature of the error.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"status_code"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Code represents the error status code (404, 403, 401, ...).")))),Object(l.b)("a",{id:"tocShealthnotreadystatus"}),Object(l.b)("h4",{id:"healthnotreadystatus"},"healthNotReadyStatus"),Object(l.b)("a",{id:"schemahealthnotreadystatus"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "errors": {\n "property1": "string",\n "property2": "string"\n }\n}\n')),Object(l.b)("h4",{id:"properties-29"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"errors"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Errors contains a list of errors that caused the not ready status.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"\xbb ",Object(l.b)("strong",{parentName:"td"},"additionalProperties")),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("a",{id:"tocShealthstatus"}),Object(l.b)("h4",{id:"healthstatus"},"healthStatus"),Object(l.b)("a",{id:"schemahealthstatus"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "status": "string"\n}\n')),Object(l.b)("h4",{id:"properties-30"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"status"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'Status always contains "ok".')))),Object(l.b)("a",{id:"tocSjsonwebkeysetgeneratorrequest"}),Object(l.b)("h4",{id:"jsonwebkeysetgeneratorrequest"},"jsonWebKeySetGeneratorRequest"),Object(l.b)("a",{id:"schemajsonwebkeysetgeneratorrequest"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "alg": "string",\n "kid": "string",\n "use": "string"\n}\n')),Object(l.b)("h4",{id:"properties-31"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'The algorithm to be used for creating the key. Supports "RS256", "ES512", "HS512", and "HS256"')),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"kid"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"The kid of the key to be created")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"use"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'The "use" (public key use) parameter identifies the intended use of',Object(l.b)("br",null),'the public key. The "use" parameter is employed to indicate whether',Object(l.b)("br",null),"a public key is used for encrypting data or verifying the signature",Object(l.b)("br",null),'on data. Valid values are "enc" and "sig".')))),Object(l.b)("a",{id:"tocSloginrequest"}),Object(l.b)("h4",{id:"loginrequest"},"loginRequest"),Object(l.b)("a",{id:"schemaloginrequest"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "challenge": "string",\n "client": {\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n },\n "oidc_context": {\n "acr_values": ["string"],\n "display": "string",\n "id_token_hint_claims": {},\n "login_hint": "string",\n "ui_locales": ["string"]\n },\n "request_url": "string",\n "requested_access_token_audience": ["string"],\n "requested_scope": ["string"],\n "session_id": "string",\n "skip": true,\n "subject": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"Contains information on an ongoing login request.")),Object(l.b)("h4",{id:"properties-32"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"challenge"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'ID is the identifier ("login challenge") of the login request. It is used to',Object(l.b)("br",null),"identify the session.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaoauth2client"},"oAuth2Client")),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"oidc_context"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemaopenidconnectcontext"},"openIDConnectContext")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"request_url"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which",Object(l.b)("br",null),"initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but",Object(l.b)("br",null),"might come in handy if you want to deal with additional request parameters.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"requested_access_token_audience"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"requested_scope"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"session_id"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"SessionID is the login session ID. If the user-agent reuses a login session (via cookie / remember flag)",Object(l.b)("br",null),"this ID will remain the same. If the user-agent did not have an existing authentication session (e.g. remember is false)",Object(l.b)("br",null),'this will be a new random value. This value is used as the "sid" parameter in the ID Token and in OIDC Front-/Back-',Object(l.b)("br",null),"channel logout. It's value can generally be used to associate consecutive login requests by a certain user.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"skip"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Skip, if true, implies that the client has requested the same scopes from the same user previously.",Object(l.b)("br",null),"If true, you can skip asking the user to grant the requested scopes, and simply forward the user to the redirect URL.",Object(l.b)("br",null),Object(l.b)("br",null),"This feature allows you to update / set session information.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"subject"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope",Object(l.b)("br",null),"requested by the OAuth 2.0 client. If this value is set and ",Object(l.b)("inlineCode",{parentName:"td"},"skip")," is true, you MUST include this subject type",Object(l.b)("br",null),"when accepting the login request, or the request will fail.")))),Object(l.b)("a",{id:"tocSlogoutrequest"}),Object(l.b)("h4",{id:"logoutrequest"},"logoutRequest"),Object(l.b)("a",{id:"schemalogoutrequest"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "request_url": "string",\n "rp_initiated": true,\n "sid": "string",\n "subject": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"Contains information about an ongoing logout request.")),Object(l.b)("h4",{id:"properties-33"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"request_url"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RequestURL is the original Logout URL requested.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"rp_initiated"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RPInitiated is set to true if the request was initiated by a Relying Party (RP), also known as an OAuth 2.0 Client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"sid"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"SessionID is the login session ID that was requested to log out.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"subject"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Subject is the user for whom the logout was request.")))),Object(l.b)("a",{id:"tocSoauth2client"}),Object(l.b)("h4",{id:"oauth2client"},"oAuth2Client"),Object(l.b)("a",{id:"schemaoauth2client"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "allowed_cors_origins": ["string"],\n "audience": ["string"],\n "backchannel_logout_session_required": true,\n "backchannel_logout_uri": "string",\n "client_id": "string",\n "client_name": "string",\n "client_secret": "string",\n "client_secret_expires_at": 0,\n "client_uri": "string",\n "contacts": ["string"],\n "created_at": "2019-08-24T14:15:22Z",\n "frontchannel_logout_session_required": true,\n "frontchannel_logout_uri": "string",\n "grant_types": ["string"],\n "jwks": {},\n "jwks_uri": "string",\n "logo_uri": "string",\n "metadata": {},\n "owner": "string",\n "policy_uri": "string",\n "post_logout_redirect_uris": ["string"],\n "redirect_uris": ["string"],\n "request_object_signing_alg": "string",\n "request_uris": ["string"],\n "response_types": ["string"],\n "scope": "string",\n "sector_identifier_uri": "string",\n "subject_type": "string",\n "token_endpoint_auth_method": "string",\n "token_endpoint_auth_signing_alg": "string",\n "tos_uri": "string",\n "updated_at": "2019-08-24T14:15:22Z",\n "userinfo_signed_response_alg": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"Client represents an OAuth 2.0 Client.")),Object(l.b)("h4",{id:"properties-34"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"allowed_cors_origins"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"audience"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"backchannel_logout_session_required"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the RP requires that a sid (session ID) Claim be included in the Logout",Object(l.b)("br",null),"Token to identify the RP session with the OP when the backchannel_logout_uri is used.",Object(l.b)("br",null),"If omitted, the default value is false.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"backchannel_logout_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RP URL that will cause the RP to log itself out when sent a Logout Token by the OP.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client_id"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ID is the id for this client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client_name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Name is the human-readable string name of the client to be presented to the",Object(l.b)("br",null),"end-user during authorization.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client_secret"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Secret is the client's secret. The secret will be included in the create request as cleartext, and then",Object(l.b)("br",null),"never again. The secret is stored using BCrypt so it is impossible to recover it. Tell your users",Object(l.b)("br",null),"that they need to write the secret down as it will not be made available again.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client_secret_expires_at"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"SecretExpiresAt is an integer holding the time at which the client",Object(l.b)("br",null),"secret will expire or 0 if it will not expire. The time is",Object(l.b)("br",null),"represented as the number of seconds from 1970-01-01T00:00:00Z as",Object(l.b)("br",null),"measured in UTC until the date/time of expiration.",Object(l.b)("br",null),Object(l.b)("br",null),"This feature is currently not supported and it's value will always",Object(l.b)("br",null),"be set to 0.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ClientURI is an URL string of a web page providing information about the client.",Object(l.b)("br",null),"If present, the server SHOULD display this URL to the end-user in",Object(l.b)("br",null),"a clickable fashion.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"contacts"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"created_at"),Object(l.b)("td",{parentName:"tr",align:null},"string(date-time)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"CreatedAt returns the timestamp of the client's creation.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"frontchannel_logout_session_required"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the RP requires that iss (issuer) and sid (session ID) query parameters be",Object(l.b)("br",null),"included to identify the RP session with the OP when the frontchannel_logout_uri is used.",Object(l.b)("br",null),"If omitted, the default value is false.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"frontchannel_logout_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"RP URL that will cause the RP to log itself out when rendered in an iframe by the OP. An iss (issuer) query",Object(l.b)("br",null),"parameter and a sid (session ID) query parameter MAY be included by the OP to enable the RP to validate the",Object(l.b)("br",null),"request and to determine which of the potentially multiple sessions is to be logged out; if either is",Object(l.b)("br",null),"included, both MUST be.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"grant_types"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"jwks"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajosejsonwebkeyset"},"JoseJSONWebKeySet")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"jwks_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL for the Client's JSON Web Key Set ","[JWK]"," document. If the Client signs requests to the Server, it contains",Object(l.b)("br",null),"the signing key(s) the Server uses to validate signatures from the Client. The JWK Set MAY also contain the",Object(l.b)("br",null),"Client's encryption keys(s), which are used by the Server to encrypt responses to the Client. When both signing",Object(l.b)("br",null),"and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all keys in the referenced",Object(l.b)("br",null),"JWK Set to indicate each key's intended usage. Although some algorithms allow the same key to be used for both",Object(l.b)("br",null),"signatures and encryption, doing so is NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used",Object(l.b)("br",null),"to provide X.509 representations of keys provided. When used, the bare key values MUST still be present and MUST",Object(l.b)("br",null),"match those in the certificate.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"logo_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"LogoURI is an URL string that references a logo for the client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"metadata"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemajsonrawmessage"},"JSONRawMessage")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"owner"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Owner is a string identifying the owner of the OAuth 2.0 Client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"policy_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"PolicyURI is a URL string that points to a human-readable privacy policy document",Object(l.b)("br",null),"that describes how the deployment organization collects, uses,",Object(l.b)("br",null),"retains, and discloses personal data.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"post_logout_redirect_uris"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"redirect_uris"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"request_object_signing_alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JWS ","[JWS]"," alg algorithm ","[JWA]"," that MUST be used for signing Request Objects sent to the OP. All Request Objects",Object(l.b)("br",null),"from this Client MUST be rejected, if not signed with this algorithm.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"request_uris"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"response_types"),Object(l.b)("td",{parentName:"tr",align:null},Object(l.b)("a",{parentName:"td",href:"#schemastringslicepipedelimiter"},"StringSlicePipeDelimiter")),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"scope"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Scope is a string containing a space-separated list of scope values (as",Object(l.b)("br",null),"described in Section 3.3 of OAuth 2.0 ","[RFC6749]",") that the client",Object(l.b)("br",null),"can use when requesting access tokens.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"sector_identifier_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL using the https scheme to be used in calculating Pseudonymous Identifiers by the OP. The URL references a",Object(l.b)("br",null),"file with a single JSON array of redirect_uri values.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"subject_type"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"SubjectType requested for responses to this Client. The subject_types_supported Discovery parameter contains a",Object(l.b)("br",null),"list of the supported subject_type values for this server. Valid types include ",Object(l.b)("inlineCode",{parentName:"td"},"pairwise")," and ",Object(l.b)("inlineCode",{parentName:"td"},"public"),".")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"token_endpoint_auth_method"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Requested Client Authentication method for the Token Endpoint. The options are client_secret_post,",Object(l.b)("br",null),"client_secret_basic, private_key_jwt, and none.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"token_endpoint_auth_signing_alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Requested Client Authentication signing algorithm for the Token Endpoint.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"tos_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"TermsOfServiceURI is a URL string that points to a human-readable terms of service",Object(l.b)("br",null),"document for the client that describes a contractual relationship",Object(l.b)("br",null),"between the end-user and the client that the end-user accepts when",Object(l.b)("br",null),"authorizing the client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"updated_at"),Object(l.b)("td",{parentName:"tr",align:null},"string(date-time)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"UpdatedAt returns the timestamp of the last update.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"userinfo_signed_response_alg"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JWS alg algorithm ","[JWA]"," REQUIRED for signing UserInfo Responses. If this is specified, the response will be JWT",Object(l.b)("br",null),"[JWT]"," serialized, and signed using JWS. The default, if omitted, is for the UserInfo Response to return the Claims",Object(l.b)("br",null),"as a UTF-8 encoded JSON object using the application/json content-type.")))),Object(l.b)("a",{id:"tocSoauth2tokenintrospection"}),Object(l.b)("h4",{id:"oauth2tokenintrospection"},"oAuth2TokenIntrospection"),Object(l.b)("a",{id:"schemaoauth2tokenintrospection"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "active": true,\n "aud": ["string"],\n "client_id": "string",\n "exp": 0,\n "ext": {},\n "iat": 0,\n "iss": "string",\n "nbf": 0,\n "obfuscated_subject": "string",\n "scope": "string",\n "sub": "string",\n "token_type": "string",\n "token_use": "string",\n "username": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"Introspection contains an access token's session data as specified by IETF RFC\n7662, see:")),Object(l.b)("h4",{id:"properties-35"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"active"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Active is a boolean indicator of whether or not the presented token",Object(l.b)("br",null),'is currently active. The specifics of a token\'s "active" state',Object(l.b)("br",null),"will vary depending on the implementation of the authorization",Object(l.b)("br",null),'server and the information it keeps about its tokens, but a "true"',Object(l.b)("br",null),'value return for the "active" property will generally indicate',Object(l.b)("br",null),"that a given token has been issued by this authorization server,",Object(l.b)("br",null),"has not been revoked by the resource owner, and is within its",Object(l.b)("br",null),"given time window of validity (e.g., after its issuance time and",Object(l.b)("br",null),"before its expiration time).")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"aud"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Audience contains a list of the token's intended audiences.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"client_id"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ID is aclient identifier for the OAuth 2.0 client that",Object(l.b)("br",null),"requested this token.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"exp"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Expires at is an integer timestamp, measured in the number of seconds",Object(l.b)("br",null),"since January 1 1970 UTC, indicating when this token will expire.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"ext"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Extra is arbitrary data set by the session.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"iat"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Issued at is an integer timestamp, measured in the number of seconds",Object(l.b)("br",null),"since January 1 1970 UTC, indicating when this token was",Object(l.b)("br",null),"originally issued.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"iss"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"IssuerURL is a string representing the issuer of this token")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"nbf"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"NotBefore is an integer timestamp, measured in the number of seconds",Object(l.b)("br",null),"since January 1 1970 UTC, indicating when this token is not to be",Object(l.b)("br",null),"used before.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"obfuscated_subject"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},'ObfuscatedSubject is set when the subject identifier algorithm was set to "pairwise" during authorization.',Object(l.b)("br",null),"It is the ",Object(l.b)("inlineCode",{parentName:"td"},"sub")," value of the ID Token that was issued.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"scope"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Scope is a JSON string containing a space-separated list of",Object(l.b)("br",null),"scopes associated with this token.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"sub"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Subject of the token, as defined in JWT ","[RFC7519]",".",Object(l.b)("br",null),"Usually a machine-readable identifier of the resource owner who",Object(l.b)("br",null),"authorized this token.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"token_type"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"TokenType is the introspected token's type, typically ",Object(l.b)("inlineCode",{parentName:"td"},"Bearer"),".")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"token_use"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"TokenUse is the introspected token's use, for example ",Object(l.b)("inlineCode",{parentName:"td"},"access_token")," or ",Object(l.b)("inlineCode",{parentName:"td"},"refresh_token"),".")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"username"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Username is a human-readable identifier for the resource owner who",Object(l.b)("br",null),"authorized this token.")))),Object(l.b)("a",{id:"tocSoauth2tokenresponse"}),Object(l.b)("h4",{id:"oauth2tokenresponse"},"oauth2TokenResponse"),Object(l.b)("a",{id:"schemaoauth2tokenresponse"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "access_token": "string",\n "expires_in": 0,\n "id_token": "string",\n "refresh_token": "string",\n "scope": "string",\n "token_type": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"The Access Token Response")),Object(l.b)("h4",{id:"properties-36"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"access_token"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"expires_in"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"id_token"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"refresh_token"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"scope"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"token_type"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"none")))),Object(l.b)("a",{id:"tocSopenidconnectcontext"}),Object(l.b)("h4",{id:"openidconnectcontext"},"openIDConnectContext"),Object(l.b)("a",{id:"schemaopenidconnectcontext"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "acr_values": ["string"],\n "display": "string",\n "id_token_hint_claims": {},\n "login_hint": "string",\n "ui_locales": ["string"]\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"Contains optional information about the OpenID Connect request.")),Object(l.b)("h4",{id:"properties-37"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"acr_values"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request.",Object(l.b)("br",null),"It is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required.",Object(l.b)("br",null),Object(l.b)("br",null),"OpenID Connect defines it as follows:",Object(l.b)("br",null),"> Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values",Object(l.b)("br",null),"that the Authorization Server is being requested to use for processing this Authentication Request, with the",Object(l.b)("br",null),"values appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication",Object(l.b)("br",null),"performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a",Object(l.b)("br",null),"Voluntary Claim by this parameter.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"display"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User.",Object(l.b)("br",null),"The defined values are:",Object(l.b)("br",null),"page: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode.",Object(l.b)("br",null),"popup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over.",Object(l.b)("br",null),"touch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface.",Object(l.b)("br",null),'wap: The Authorization Server SHOULD display the authentication and consent UI consistent with a "feature phone" type display.',Object(l.b)("br",null),Object(l.b)("br",null),"The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"id_token_hint_claims"),Object(l.b)("td",{parentName:"tr",align:null},"object"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"IDTokenHintClaims are the claims of the ID Token previously issued by the Authorization Server being passed as a hint about the",Object(l.b)("br",null),"End-User's current or past authenticated session with the Client.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"login_hint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"LoginHint hints about the login identifier the End-User might use to log in (if necessary).",Object(l.b)("br",null),"This hint can be used by an RP if it first asks the End-User for their e-mail address (or other identifier)",Object(l.b)("br",null),"and then wants to pass that value as a hint to the discovered authorization service. This value MAY also be a",Object(l.b)("br",null),"phone number in the format specified for the phone_number Claim. The use of this parameter is optional.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"ui_locales"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a",Object(l.b)("br",null),"space-separated list of BCP47 ","[RFC5646]"," language tag values, ordered by preference. For instance, the value",Object(l.b)("br",null),'"fr-CA fr en" represents a preference for French as spoken in Canada, then French (without a region designation),',Object(l.b)("br",null),"followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested",Object(l.b)("br",null),"locales are not supported by the OpenID Provider.")))),Object(l.b)("a",{id:"tocSrejectrequest"}),Object(l.b)("h4",{id:"rejectrequest"},"rejectRequest"),Object(l.b)("a",{id:"schemarejectrequest"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "error": "string",\n "error_debug": "string",\n "error_description": "string",\n "error_hint": "string",\n "status_code": 0\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"The request payload used to accept a login or consent request.")),Object(l.b)("h4",{id:"properties-38"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"error"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"The error should follow the OAuth2 error format (e.g. ",Object(l.b)("inlineCode",{parentName:"td"},"invalid_request"),", ",Object(l.b)("inlineCode",{parentName:"td"},"login_required"),").",Object(l.b)("br",null),Object(l.b)("br",null),"Defaults to ",Object(l.b)("inlineCode",{parentName:"td"},"request_denied"),".")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"error_debug"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Debug contains information to help resolve the problem as a developer. Usually not exposed",Object(l.b)("br",null),"to the public but only in the server logs.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"error_description"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Description of the error in a human readable format.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"error_hint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Hint to help resolve the error.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"status_code"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Represents the HTTP status code of the error (e.g. 401 or 403)",Object(l.b)("br",null),Object(l.b)("br",null),"Defaults to 400")))),Object(l.b)("a",{id:"tocSuserinforesponse"}),Object(l.b)("h4",{id:"userinforesponse"},"userinfoResponse"),Object(l.b)("a",{id:"schemauserinforesponse"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "birthdate": "string",\n "email": "string",\n "email_verified": true,\n "family_name": "string",\n "gender": "string",\n "given_name": "string",\n "locale": "string",\n "middle_name": "string",\n "name": "string",\n "nickname": "string",\n "phone_number": "string",\n "phone_number_verified": true,\n "picture": "string",\n "preferred_username": "string",\n "profile": "string",\n "sub": "string",\n "updated_at": 0,\n "website": "string",\n "zoneinfo": "string"\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"The userinfo response")),Object(l.b)("h4",{id:"properties-39"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"birthdate"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"End-User's birthday, represented as an ISO 8601:2004 ","[ISO8601\u20112004]"," YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"email"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 ","[RFC5322]"," addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"email_verified"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"family_name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"gender"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"given_name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"locale"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"End-User's locale, represented as a BCP47 ","[RFC5646]"," language tag. This is typically an ISO 639-1 Alpha-2 ","[ISO639\u20111]"," language code in lowercase and an ISO 3166-1 Alpha-2 ","[ISO3166\u20111]"," country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; Relying Parties MAY choose to accept this locale syntax as well.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"middle_name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"name"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"nickname"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"phone_number"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"End-User's preferred telephone number. E.164 ","[E.164]"," is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 ","[RFC3966]"," extension syntax, for example, +1 (604) 555-1234;ext=5678.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"phone_number_verified"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed. The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"picture"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"preferred_username"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Non-unique shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"profile"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"sub"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Subject - Identifier for the End-User at the IssuerURL.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"updated_at"),Object(l.b)("td",{parentName:"tr",align:null},"integer(int64)"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"website"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"zoneinfo"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"String from zoneinfo ","[zoneinfo]"," time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles.")))),Object(l.b)("a",{id:"tocSversion"}),Object(l.b)("h4",{id:"version"},"version"),Object(l.b)("a",{id:"schemaversion"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "version": "string"\n}\n')),Object(l.b)("h4",{id:"properties-40"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"version"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Version is the service's version.")))),Object(l.b)("a",{id:"tocSwellknown"}),Object(l.b)("h4",{id:"wellknown"},"wellKnown"),Object(l.b)("a",{id:"schemawellknown"}),Object(l.b)("pre",null,Object(l.b)("code",{parentName:"pre",className:"language-json"},'{\n "authorization_endpoint": "https://playground.ory.sh/ory-hydra/public/oauth2/auth",\n "backchannel_logout_session_supported": true,\n "backchannel_logout_supported": true,\n "claims_parameter_supported": true,\n "claims_supported": ["string"],\n "end_session_endpoint": "string",\n "frontchannel_logout_session_supported": true,\n "frontchannel_logout_supported": true,\n "grant_types_supported": ["string"],\n "id_token_signing_alg_values_supported": ["string"],\n "issuer": "https://playground.ory.sh/ory-hydra/public/",\n "jwks_uri": "https://playground.ory.sh/ory-hydra/public/.well-known/jwks.json",\n "registration_endpoint": "https://playground.ory.sh/ory-hydra/admin/client",\n "request_object_signing_alg_values_supported": ["string"],\n "request_parameter_supported": true,\n "request_uri_parameter_supported": true,\n "require_request_uri_registration": true,\n "response_modes_supported": ["string"],\n "response_types_supported": ["string"],\n "revocation_endpoint": "string",\n "scopes_supported": ["string"],\n "subject_types_supported": ["string"],\n "token_endpoint": "https://playground.ory.sh/ory-hydra/public/oauth2/token",\n "token_endpoint_auth_methods_supported": ["string"],\n "userinfo_endpoint": "string",\n "userinfo_signing_alg_values_supported": ["string"]\n}\n')),Object(l.b)("p",null,Object(l.b)("em",{parentName:"p"},"WellKnown represents important OpenID Connect discovery metadata")),Object(l.b)("h4",{id:"properties-41"},"Properties"),Object(l.b)("table",null,Object(l.b)("thead",{parentName:"table"},Object(l.b)("tr",{parentName:"thead"},Object(l.b)("th",{parentName:"tr",align:null},"Name"),Object(l.b)("th",{parentName:"tr",align:null},"Type"),Object(l.b)("th",{parentName:"tr",align:null},"Required"),Object(l.b)("th",{parentName:"tr",align:null},"Restrictions"),Object(l.b)("th",{parentName:"tr",align:null},"Description"))),Object(l.b)("tbody",{parentName:"table"},Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"authorization_endpoint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL of the OP's OAuth 2.0 Authorization Endpoint.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"backchannel_logout_session_supported"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the OP can pass a sid (session ID) Claim in the Logout Token to identify the RP",Object(l.b)("br",null),"session with the OP. If supported, the sid Claim is also included in ID Tokens issued by the OP")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"backchannel_logout_supported"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the OP supports back-channel logout, with true indicating support.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"claims_parameter_supported"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the OP supports use of the claims parameter, with true indicating support.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"claims_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JSON array containing a list of the Claim Names of the Claims that the OpenID Provider MAY be able to supply",Object(l.b)("br",null),"values for. Note that for privacy or other reasons, this might not be an exhaustive list.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"end_session_endpoint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL at the OP to which an RP can perform a redirect to request that the End-User be logged out at the OP.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"frontchannel_logout_session_supported"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the OP can pass iss (issuer) and sid (session ID) query parameters to identify",Object(l.b)("br",null),"the RP session with the OP when the frontchannel_logout_uri is used. If supported, the sid Claim is also",Object(l.b)("br",null),"included in ID Tokens issued by the OP.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"frontchannel_logout_supported"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the OP supports HTTP-based logout, with true indicating support.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"grant_types_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JSON array containing a list of the OAuth 2.0 Grant Type values that this OP supports.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"id_token_signing_alg_values_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token",Object(l.b)("br",null),"to encode the Claims in a JWT.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"issuer"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL using the https scheme with no query or fragment component that the OP asserts as its IssuerURL Identifier.",Object(l.b)("br",null),"If IssuerURL discovery is supported , this value MUST be identical to the issuer value returned",Object(l.b)("br",null),"by WebFinger. This also MUST be identical to the iss Claim value in ID Tokens issued from this IssuerURL.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"jwks_uri"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL of the OP's JSON Web Key Set ","[JWK]"," document. This contains the signing key(s) the RP uses to validate",Object(l.b)("br",null),"signatures from the OP. The JWK Set MAY also contain the Server's encryption key(s), which are used by RPs",Object(l.b)("br",null),"to encrypt requests to the Server. When both signing and encryption keys are made available, a use (Key Use)",Object(l.b)("br",null),"parameter value is REQUIRED for all keys in the referenced JWK Set to indicate each key's intended usage.",Object(l.b)("br",null),"Although some algorithms allow the same key to be used for both signatures and encryption, doing so is",Object(l.b)("br",null),"NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 representations of",Object(l.b)("br",null),"keys provided. When used, the bare key values MUST still be present and MUST match those in the certificate.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"registration_endpoint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL of the OP's Dynamic Client Registration Endpoint.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"request_object_signing_alg_values_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for Request Objects,",Object(l.b)("br",null),"which are described in Section 6.1 of OpenID Connect Core 1.0 ","[OpenID.Core]",". These algorithms are used both when",Object(l.b)("br",null),"the Request Object is passed by value (using the request parameter) and when it is passed by reference",Object(l.b)("br",null),"(using the request_uri parameter).")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"request_parameter_supported"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the OP supports use of the request parameter, with true indicating support.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"request_uri_parameter_supported"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the OP supports use of the request_uri parameter, with true indicating support.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"require_request_uri_registration"),Object(l.b)("td",{parentName:"tr",align:null},"boolean"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"Boolean value specifying whether the OP requires any request_uri values used to be pre-registered",Object(l.b)("br",null),"using the request_uris registration parameter.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"response_modes_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JSON array containing a list of the OAuth 2.0 response_mode values that this OP supports.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"response_types_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID",Object(l.b)("br",null),"Providers MUST support the code, id_token, and the token id_token Response Type values.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"revocation_endpoint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL of the authorization server's OAuth 2.0 revocation endpoint.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"scopes_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"SON array containing a list of the OAuth 2.0 ","[RFC6749]"," scope values that this server supports. The server MUST",Object(l.b)("br",null),"support the openid scope value. Servers MAY choose not to advertise some supported scope values even when this parameter is used")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"subject_types_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include",Object(l.b)("br",null),"pairwise and public.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"token_endpoint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"true"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL of the OP's OAuth 2.0 Token Endpoint")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"token_endpoint_auth_methods_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JSON array containing a list of Client Authentication methods supported by this Token Endpoint. The options are",Object(l.b)("br",null),"client_secret_post, client_secret_basic, client_secret_jwt, and private_key_jwt, as described in Section 9 of OpenID Connect Core 1.0")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"userinfo_endpoint"),Object(l.b)("td",{parentName:"tr",align:null},"string"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"URL of the OP's UserInfo Endpoint.")),Object(l.b)("tr",{parentName:"tbody"},Object(l.b)("td",{parentName:"tr",align:null},"userinfo_signing_alg_values_supported"),Object(l.b)("td",{parentName:"tr",align:null},"[string]"),Object(l.b)("td",{parentName:"tr",align:null},"false"),Object(l.b)("td",{parentName:"tr",align:null},"none"),Object(l.b)("td",{parentName:"tr",align:null},"JSON array containing a list of the JWS ","[JWS]"," signing algorithms (alg values) ","[JWA]"," supported by the UserInfo Endpoint to encode the Claims in a JWT ","[JWT]",".")))))}u.isMDXComponent=!0},568:function(e,t,n){"use strict";n.d(t,"a",(function(){return p})),n.d(t,"b",(function(){return m}));var a=n(0),r=n.n(a);function l(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function
(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?b(Object(n),!0).forEach((function(t){l(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):b(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t){if(null==e)return{};var n,a,r=function(e,t){if(null==e)return{};var n,a,r={},l=Object.keys(e);for(a=0;a<l.length;a++)n=l[a],t.indexOf(n)>=0||(r[n]=e[n]);return r}(e,t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(a=0;a<l.length;a++)n=l[a],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}var c=r.a.createContext({}),o=function(e){var t=r.a.useContext(c),n=t;return e&&(n="function"==typeof e?e(t):i(i({},t),e)),n},p=function(e){var t=o(e.components);return r.a.createElement(c.Provider,{value:t},e.children)},u={inlineCode:"code",wrapper:function(e){var t=e.children;return r.a.createElement(r.a.Fragment,{},t)}},d=r.a.forwardRef((function(e,t){var n=e.components,a=e.mdxType,l=e.originalType,b=e.parentName,c=s(e,["components","mdxType","originalType","parentName"]),p=o(n),d=a,m=p["".concat(b,".").concat(d)]||p[d]||u[d]||l;return n?r.a.createElement(m,i(i({ref:t},c),{},{components:n})):r.a.createElement(m,i({ref:t},c))}));function m(e,t){var n=arguments,a=t&&t.mdxType;if("string"==typeof e||a){var l=n.length,b=new Array(l);b[0]=d;var i={};for(var s in t)hasOwnProperty.call(t,s)&&(i[s]=t[s]);i.originalType=e,i.mdxType="string"==typeof e?e:a,b[1]=i;for(var c=2;c<l;c++)b[c]=n[c];return r.a.createElement.apply(null,b)}return r.a.createElement.apply(null,n)}d.displayName="MDXCreateElement"},571:function(e,t,n){"use strict";function a(e){var t,n,r="";if("string"==typeof e||"number"==typeof e)r+=e;else if("object"==typeof e)if(Array.isArray(e))for(t=0;t<e.length;t++)e[t]&&(n=a(e[t]))&&(r&&(r+=" "),r+=n);else for(t in e)e[t]&&(r&&(r+=" "),r+=t);return r}t.a=function(){for(var e,t,n=0,r="";n<arguments.length;)(e=arguments[n++])&&(t=a(e))&&(r&&(r+=" "),r+=t);return r}},572:function(e,t,n){"use strict";var a=n(0),r=n.n(a),l=n(577),b=n(571),i=n(56),s=n.n(i);var c=37,o=39;t.a=function(e){var t=e.lazy,n=e.block,i=e.defaultValue,p=e.values,u=e.groupId,d=e.className,m=Object(l.a)(),g=m.tabGroupChoices,j=m.setTabGroupChoices,O=Object(a.useState)(i),h=O[0],N=O[1],y=a.Children.toArray(e.children),f=[];if(null!=u){var v=g[u];null!=v&&v!==h&&p.some((function(e){return e.value===v}))&&N(v)}var T=function(e){var t=e.target,n=f.indexOf(t),a=y[n].props.value;N(a),null!=u&&(j(u,a),setTimeout((function(){var e,n,a,r,l,b,i,c;(e=t.getBoundingClientRect(),n=e.top,a=e.left,r=e.bottom,l=e.right,b=window,i=b.innerHeight,c=b.innerWidth,n>=0&&l<=c&&r<=i&&a>=0)||(t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.add(s.a.tabItemActive),setTimeout((function(){return t.classList.remove(s.a.tabItemActive)}),2e3))}),150))},_=function(e){var t,n;switch(e.keyCode){case o:var a=f.indexOf(e.target)+1;n=f[a]||f[0];break;case c:var r=f.indexOf(e.target)-1;n=f[r]||f[f.length-1]}null===(t=n)||void 0===t||t.focus()};return r.a.createElement("div",{className:"tabs-container"},r.a.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:Object(b.a)("tabs",{"tabs--block":n},d)},p.map((function(e){var t=e.value,n=e.label;return r.a.createElement("li",{role:"tab",tabIndex:h===t?0:-1,"aria-selected":h===t,className:Object(b.a)("tabs__item",s.a.tabItem,{"tabs__item--active":h===t}),key:t,ref:function(e){return f.push(e)},onKeyDown:_,onFocus:T,onClick:T},n)}))),t?Object(a.cloneElement)(y.filter((function(e){return e.props.value===h}))[0],{className:"margin-vert--md"}):r.a.createElement("div",{className:"margin-vert--md"},y.map((function(e,t){return Object(a.cloneElement)(e,{key:t,hidden:e.props.value!==h})}))))}},573:function(e,t,n){"use strict";var a=n(0),r=n.n(a);t.a=function(e){var t=e.children,n=e.hidden,a=e.className;return r.a.createElement("div",{role:"tabpanel",hidden:n,className:a},t)}},577:function(e,t,n){"use strict";var a=n(0),r=n(578);t.a=function(){var e=Object(a.useContext)(r.a);if(null==e)throw new Error("`useUserPreferencesContext` is used outside of `Layout` Component.");return e}},578:function(e,t,n){"use strict";var a=n(0),r=Object(a.createContext)(void 0);t.a=r}}]);
b
test_client.py
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import json from datetime import datetime import pendulum import pytest from airbyte_cdk.models import SyncMode from facebook_business import FacebookAdsApi, FacebookSession from facebook_business.exceptions import FacebookRequestError from source_facebook_marketing.api import API from source_facebook_marketing.streams import AdCreatives, Campaigns FB_API_VERSION = FacebookAdsApi.API_VERSION @pytest.fixture(scope="session", name="account_id") def account_id_fixture(): return "unknown_account" @pytest.fixture(scope="session", name="some_config") def some_config_fixture(account_id): return {"start_date": "2021-01-23T00:00:00Z", "account_id": f"{account_id}", "access_token": "unknown_token"} @pytest.fixture(autouse=True) def mock_default_sleep_interval(mocker): mocker.patch("source_facebook_marketing.streams.common.DEFAULT_SLEEP_INTERVAL", return_value=pendulum.duration(seconds=5)) @pytest.fixture(name="api") def api_fixture(some_config, requests_mock, fb_account_response): api = API(account_id=some_config["account_id"], access_token=some_config["access_token"]) requests_mock.register_uri("GET", FacebookSession.GRAPH + f"/{FB_API_VERSION}/me/adaccounts", [fb_account_response]) return api
error = { "message": ( "(#80000) There have been too many calls from this ad-account. Wait a bit and try again. " "For more info, please refer to https://developers.facebook.com/docs/graph-api/overview/rate-limiting." ), "type": "OAuthException", "code": 80000, "error_subcode": 2446079, "fbtrace_id": "this_is_fake_response", } headers = {"x-app-usage": json.dumps({"call_count": 28, "total_time": 25, "total_cputime": 25})} return { "json": { "error": error, }, "status_code": 400, "headers": headers, } @pytest.fixture(name="fb_account_response") def fb_account_response_fixture(account_id): return { "json": { "data": [ { "account_id": account_id, "id": f"act_{account_id}", } ], "paging": {"cursors": {"before": "MjM4NDYzMDYyMTcyNTAwNzEZD", "after": "MjM4NDYzMDYyMTcyNTAwNzEZD"}}, }, "status_code": 200, } class TestBackoff: def test_limit_reached(self, mocker, requests_mock, api, fb_call_rate_response, account_id): """Error once, check that we retry and not fail""" # turn Campaigns into non batch mode to test non batch logic mocker.patch.object(Campaigns, "use_batch", new_callable=mocker.PropertyMock, return_value=False) campaign_responses = [ fb_call_rate_response, { "json": {"data": [{"id": 1, "updated_time": "2020-09-25T00:00:00Z"}, {"id": 2, "updated_time": "2020-09-25T00:00:00Z"}]}, "status_code": 200, }, ] requests_mock.register_uri("GET", FacebookSession.GRAPH + f"/{FB_API_VERSION}/act_{account_id}/campaigns", campaign_responses) requests_mock.register_uri("GET", FacebookSession.GRAPH + f"/{FB_API_VERSION}/1/", [{"status_code": 200}]) requests_mock.register_uri("GET", FacebookSession.GRAPH + f"/{FB_API_VERSION}/2/", [{"status_code": 200}]) stream = Campaigns(api=api, start_date=pendulum.now(), end_date=pendulum.now(), include_deleted=False) try: records = list(stream.read_records(sync_mode=SyncMode.full_refresh, stream_state={})) assert records except FacebookRequestError: pytest.fail("Call rate error has not being handled") def test_batch_limit_reached(self, requests_mock, api, fb_call_rate_response, account_id): """Error once, check that we retry and not fail""" responses = [ fb_call_rate_response, { "json": { "data": [ { "id": "123", "object_type": "SHARE", "status": "ACTIVE", }, { "id": "1234", "object_type": "SHARE", "status": "ACTIVE", }, ], "status_code": 200, } }, ] batch_responses = [ fb_call_rate_response, { "json": [ {"body": json.dumps({"name": "creative 1"}), "code": 200, "headers": {}}, {"body": json.dumps({"name": "creative 2"}), "code": 200, "headers": {}}, ] }, ] requests_mock.register_uri("GET", FacebookSession.GRAPH + f"/{FB_API_VERSION}/act_{account_id}/adcreatives", responses) requests_mock.register_uri("POST", FacebookSession.GRAPH + f"/{FB_API_VERSION}/", batch_responses) stream = AdCreatives(api=api, include_deleted=False) records = list(stream.read_records(sync_mode=SyncMode.full_refresh, stream_state={})) assert records == [{"name": "creative 1"}, {"name": "creative 2"}] def test_server_error(self, requests_mock, api, account_id): """Error once, check that we retry and not fail""" responses = [ {"json": {"error": {}}, "status_code": 500}, { "json": {"data": [{"id": 1, "updated_time": "2020-09-25T00:00:00Z"}, {"id": 2, "updated_time": "2020-09-25T00:00:00Z"}]}, "status_code": 200, }, ] requests_mock.register_uri("GET", FacebookSession.GRAPH + f"/{FB_API_VERSION}/act_{account_id}/campaigns", responses) with pytest.raises(FacebookRequestError): stream = Campaigns(api=api, start_date=datetime.now(), end_date=datetime.now(), include_deleted=False) list(stream.read_records(sync_mode=SyncMode.full_refresh, stream_state={}))
@pytest.fixture(name="fb_call_rate_response") def fb_call_rate_response_fixture():
strings1.rs
// strings1.rs // Make me compile without changing the function signature! // Execute `rustlings hint strings1` for hints ;) fn main() { let answer = current_favorite_color(); println!("My current favorite color is {}", answer); } fn current_favorite_color() -> String { String::from("blue") }
// destroyed once it's returned. Instead, use String.
// Usually, you can't return &str. It is a reference, so it will be
FourCircledMediUltraLight.tsx
import * as React from "react"; import Svg, { Path } from "react-native-svg"; type Props = { size?: number | string; color?: string; }; function
({ size = 16, color = "currentColor", }: Props): JSX.Element { return ( <Svg width={size} height={size} viewBox="0 0 24 24" fill="none"> <Path d="M12.792 11.856v1.8h-3.72l3.456-5.184h.264v3.384zM5.76 21h12.48v-.84H5.76V21zm0-17.16h12.48V3H5.76v.84zM8.256 14.4h4.536v2.064h.816V14.4h1.464v-.744h-1.464V7.584h-1.32l-4.032 6.048v.768z" fill={color} /> </Svg> ); } export default FourCircledMediUltraLight;
FourCircledMediUltraLight
app.rs
use std::collections::HashSet; use std::env; use std::path::Path; use std::str::FromStr; use atty::{self, Stream}; use crate::{ clap_app, config::{get_args_from_config_file, get_args_from_env_var}, }; use clap::ArgMatches; use console::Term; use crate::input::{new_file_input, new_stdin_input}; use bat::{ assets::HighlightingAssets, bat_warning, config::{Config, VisibleLines}, error::*, input::Input, line_range::{HighlightedLineRanges, LineRange, LineRanges}, style::{StyleComponent, StyleComponents}, MappingTarget, PagingMode, SyntaxMapping, WrappingMode, }; fn is_truecolor_terminal() -> bool { env::var("COLORTERM") .map(|colorterm| colorterm == "truecolor" || colorterm == "24bit") .unwrap_or(false) } pub struct App { pub matches: ArgMatches<'static>, interactive_output: bool, } impl App { pub fn new() -> Result<Self> { #[cfg(windows)] let _ = ansi_term::enable_ansi_support(); let interactive_output = atty::is(Stream::Stdout); Ok(App { matches: Self::matches(interactive_output)?, interactive_output, }) } fn matches(interactive_output: bool) -> Result<ArgMatches<'static>> { let args = if wild::args_os().nth(1) == Some("cache".into()) || wild::args_os().any(|arg| arg == "--no-config") { // Skip the arguments in bats config file wild::args_os().collect::<Vec<_>>() } else { let mut cli_args = wild::args_os(); // Read arguments from bats config file let mut args = get_args_from_env_var() .unwrap_or_else(get_args_from_config_file) .chain_err(|| "Could not parse configuration file")?; // Put the zero-th CLI argument (program name) first args.insert(0, cli_args.next().unwrap()); // .. and the rest at the end cli_args.for_each(|a| args.push(a)); args }; Ok(clap_app::build_app(interactive_output).get_matches_from(args)) } pub fn config(&self, inputs: &[Input]) -> Result<Config> { let style_components = self.style_components()?; let paging_mode = match self.matches.value_of("paging") { Some("always") => PagingMode::Always, Some("never") => PagingMode::Never, Some("auto") | None => { // If we have -pp as an option when in auto mode, the pager should be disabled. let extra_plain = self.matches.occurrences_of("plain") > 1; if extra_plain || self.matches.is_present("no-paging") { PagingMode::Never } else if inputs.iter().any(Input::is_stdin) { // If we are reading from stdin, only enable paging if we write to an // interactive terminal and if we do not *read* from an interactive // terminal. if self.interactive_output && !atty::is(Stream::Stdin) { PagingMode::QuitIfOneScreen } else { PagingMode::Never } } else if self.interactive_output { PagingMode::QuitIfOneScreen } else { PagingMode::Never } } _ => unreachable!("other values for --paging are not allowed"), }; let mut syntax_mapping = SyntaxMapping::builtin(); if let Some(values) = self.matches.values_of("map-syntax") { for from_to in values { let parts: Vec<_> = from_to.split(':').collect(); if parts.len() != 2 { return Err("Invalid syntax mapping. The format of the -m/--map-syntax option is '<glob-pattern>:<syntax-name>'. For example: '*.cpp:C++'.".into()); } syntax_mapping.insert(parts[0], MappingTarget::MapTo(parts[1]))?; } } let maybe_term_width = self.matches.value_of("terminal-width").and_then(|w| { if w.starts_with('+') || w.starts_with('-') { // Treat argument as a delta to the current terminal width w.parse().ok().map(|delta: i16| { let old_width: u16 = Term::stdout().size().1; let new_width: i32 = i32::from(old_width) + i32::from(delta); if new_width <= 0 { old_width as usize } else { new_width as usize } }) } else { w.parse().ok() } }); Ok(Config { true_color: is_truecolor_terminal(), language: self.matches.value_of("language").or_else(|| { if self.matches.is_present("show-all") { Some("show-nonprintable") } else { None } }), show_nonprintable: self.matches.is_present("show-all"), wrapping_mode: if self.interactive_output || maybe_term_width.is_some() { match self.matches.value_of("wrap") { Some("character") => WrappingMode::Character, Some("never") => WrappingMode::NoWrapping(true), Some("auto") | None => { if style_components.plain() { WrappingMode::NoWrapping(false) } else { WrappingMode::Character } } _ => unreachable!("other values for --paging are not allowed"), } } else { // We don't have the tty width when piping to another program. // There's no point in wrapping when this is the case. WrappingMode::NoWrapping(false) }, colored_output: self.matches.is_present("force-colorization") || match self.matches.value_of("color") { Some("always") => true, Some("never") => false, Some("auto") => env::var_os("NO_COLOR").is_none() && self.interactive_output, _ => unreachable!("other values for --color are not allowed"), }, paging_mode, term_width: maybe_term_width.unwrap_or(Term::stdout().size().1 as usize), loop_through: !(self.interactive_output || self.matches.value_of("color") == Some("always") || self.matches.value_of("decorations") == Some("always") || self.matches.is_present("force-colorization")), tab_width: self .matches .value_of("tabs") .map(String::from) .or_else(|| env::var("BAT_TABS").ok()) .and_then(|t| t.parse().ok()) .unwrap_or( if style_components.plain() && paging_mode == PagingMode::Never { 0 } else { 4 }, ), theme: self .matches .value_of("theme") .map(String::from) .or_else(|| env::var("BAT_THEME").ok()) .map(|s| { if s == "default" { String::from(HighlightingAssets::default_theme()) } else { s } }) .unwrap_or_else(|| String::from(HighlightingAssets::default_theme())), visible_lines: match self.matches.is_present("diff") { #[cfg(feature = "git")] true => VisibleLines::DiffContext( self.matches .value_of("diff-context") .and_then(|t| t.parse().ok()) .unwrap_or(2), ), _ => VisibleLines::Ranges( self.matches .values_of("line-range") .map(|vs| vs.map(LineRange::from).collect()) .transpose()? .map(LineRanges::from) .unwrap_or_default(), ), }, style_components, syntax_mapping, pager: self.matches.value_of("pager"), use_italic_text: self.matches.value_of("italic-text") == Some("always"), highlighted_lines: self .matches .values_of("highlight-line") .map(|ws| ws.map(LineRange::from).collect()) .transpose()? .map(LineRanges::from) .map(HighlightedLineRanges) .unwrap_or_default(), use_custom_assets: !self.matches.is_present("no-custom-assets"), }) } pub fn inputs(&self) -> Result<Vec<Input>> { // verify equal length of file-names and input FILEs match self.matches.values_of("file-name") { Some(ref filenames) if self.matches.values_of_os("FILE").is_some() && filenames.len() != self.matches.values_of_os("FILE").unwrap().len() =>
_ => {} } let filenames: Option<Vec<&Path>> = self .matches .values_of_os("file-name") .map(|values| values.map(Path::new).collect()); let mut filenames_or_none: Box<dyn Iterator<Item = Option<&Path>>> = match filenames { Some(filenames) => Box::new(filenames.into_iter().map(Some)), None => Box::new(std::iter::repeat(None)), }; let files: Option<Vec<&Path>> = self .matches .values_of_os("FILE") .map(|vs| vs.map(Path::new).collect()); if files.is_none() { return Ok(vec![new_stdin_input( filenames_or_none.next().unwrap_or(None), )]); } let files_or_none: Box<dyn Iterator<Item = _>> = match files { Some(ref files) => Box::new(files.iter().map(|name| Some(*name))), None => Box::new(std::iter::repeat(None)), }; let mut file_input = Vec::new(); for (filepath, provided_name) in files_or_none.zip(filenames_or_none) { if let Some(filepath) = filepath { if filepath.to_str().unwrap_or_default() == "-" { file_input.push(new_stdin_input(provided_name)); } else { file_input.push(new_file_input(filepath, provided_name)); } } } Ok(file_input) } fn style_components(&self) -> Result<StyleComponents> { let matches = &self.matches; let mut styled_components = StyleComponents(if matches.value_of("decorations") == Some("never") { HashSet::new() } else if matches.is_present("number") { [StyleComponent::LineNumbers].iter().cloned().collect() } else if matches.is_present("plain") { [StyleComponent::Plain].iter().cloned().collect() } else { let env_style_components: Option<Vec<StyleComponent>> = env::var("BAT_STYLE") .ok() .map(|style_str| { style_str .split(',') .map(|x| StyleComponent::from_str(&x)) .collect::<Result<Vec<StyleComponent>>>() }) .transpose()?; matches .value_of("style") .map(|styles| { styles .split(',') .map(|style| style.parse::<StyleComponent>()) .filter_map(|style| style.ok()) .collect::<Vec<_>>() }) .or(env_style_components) .unwrap_or_else(|| vec![StyleComponent::Full]) .into_iter() .map(|style| style.components(self.interactive_output)) .fold(HashSet::new(), |mut acc, components| { acc.extend(components.iter().cloned()); acc }) }); // If `grid` is set, remove `rule` as it is a subset of `grid`, and print a warning. if styled_components.grid() && styled_components.0.remove(&StyleComponent::Rule) { bat_warning!("Style 'rule' is a subset of style 'grid', 'rule' will not be visible."); } Ok(styled_components) } }
{ return Err("Must be one file name per input type.".into()); }
media_player.py
"""Media Player component to integrate TVs exposing the Joint Space API.""" from datetime import timedelta import logging from haphilipsjs import PhilipsTV import voluptuous as vol from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity from homeassistant.components.media_player.const import ( MEDIA_TYPE_CHANNEL, SUPPORT_NEXT_TRACK, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_STEP, ) from homeassistant.const import ( CONF_API_VERSION, CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import call_later, track_time_interval from homeassistant.helpers.script import Script _LOGGER = logging.getLogger(__name__) SUPPORT_PHILIPS_JS = ( SUPPORT_TURN_OFF | SUPPORT_VOLUME_STEP | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | SUPPORT_SELECT_SOURCE | SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK | SUPPORT_PLAY_MEDIA ) CONF_ON_ACTION = "turn_on_action" DEFAULT_NAME = "Philips TV" DEFAULT_API_VERSION = "1" DEFAULT_SCAN_INTERVAL = 30 DELAY_ACTION_DEFAULT = 2.0 DELAY_ACTION_ON = 10.0 PREFIX_SEPARATOR = ": " PREFIX_SOURCE = "Input" PREFIX_CHANNEL = "Channel" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_API_VERSION, default=DEFAULT_API_VERSION): cv.string, vol.Optional(CONF_ON_ACTION): cv.SCRIPT_SCHEMA, } ) def _inverted(data): return {v: k for k, v in data.items()} def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Philips TV platform.""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) api_version = config.get(CONF_API_VERSION) turn_on_action = config.get(CONF_ON_ACTION) tvapi = PhilipsTV(host, api_version) on_script = Script(hass, turn_on_action) if turn_on_action else None add_entities([PhilipsTVMediaPlayer(tvapi, name, on_script)]) class PhilipsTVMediaPlayer(MediaPlayerEntity): """Representation of a Philips TV exposing the JointSpace API.""" def __init__(self, tv, name, on_script): """Initialize the Philips TV.""" self._tv = tv self._name = name self._sources = {} self._channels = {} self._on_script = on_script self._supports = SUPPORT_PHILIPS_JS if self._on_script: self._supports |= SUPPORT_TURN_ON self._update_task = None def _update_soon(self, delay): """Reschedule update task.""" if self._update_task: self._update_task() self._update_task = None self.schedule_update_ha_state(force_refresh=False) def update_forced(event_time): self.schedule_update_ha_state(force_refresh=True) def update_and_restart(event_time): update_forced(event_time) self._update_task = track_time_interval( self.hass, update_forced, timedelta(seconds=DEFAULT_SCAN_INTERVAL) ) call_later(self.hass, delay, update_and_restart) async def async_added_to_hass(self): """Start running updates once we are added to hass.""" await self.hass.async_add_executor_job(self._update_soon, 0) @property def name(self): """Return the device name.""" return self._name @property def should_poll(self): """Device should be polled.""" return False @property def supported_features(self): """Flag media player features that are supported.""" return self._supports @property def state(self):
@property def source(self): """Return the current input source.""" if self.media_content_type == MEDIA_TYPE_CHANNEL: name = self._channels.get(self._tv.channel_id) prefix = PREFIX_CHANNEL else: name = self._sources.get(self._tv.source_id) prefix = PREFIX_SOURCE if name is None: return None return prefix + PREFIX_SEPARATOR + name @property def source_list(self): """List of available input sources.""" complete = [] for source in self._sources.values(): complete.append(PREFIX_SOURCE + PREFIX_SEPARATOR + source) for channel in self._channels.values(): complete.append(PREFIX_CHANNEL + PREFIX_SEPARATOR + channel) return complete def select_source(self, source): """Set the input source.""" data = source.split(PREFIX_SEPARATOR, 1) if data[0] == PREFIX_SOURCE: source_id = _inverted(self._sources).get(data[1]) if source_id: self._tv.setSource(source_id) elif data[0] == PREFIX_CHANNEL: channel_id = _inverted(self._channels).get(data[1]) if channel_id: self._tv.setChannel(channel_id) self._update_soon(DELAY_ACTION_DEFAULT) @property def volume_level(self): """Volume level of the media player (0..1).""" return self._tv.volume @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._tv.muted def turn_on(self): """Turn on the device.""" if self._on_script: self._on_script.run() self._update_soon(DELAY_ACTION_ON) def turn_off(self): """Turn off the device.""" self._tv.sendKey("Standby") self._tv.on = False self._update_soon(DELAY_ACTION_DEFAULT) def volume_up(self): """Send volume up command.""" self._tv.sendKey("VolumeUp") self._update_soon(DELAY_ACTION_DEFAULT) def volume_down(self): """Send volume down command.""" self._tv.sendKey("VolumeDown") self._update_soon(DELAY_ACTION_DEFAULT) def mute_volume(self, mute): """Send mute command.""" self._tv.setVolume(None, mute) self._update_soon(DELAY_ACTION_DEFAULT) def set_volume_level(self, volume): """Set volume level, range 0..1.""" self._tv.setVolume(volume, self._tv.muted) self._update_soon(DELAY_ACTION_DEFAULT) def media_previous_track(self): """Send rewind command.""" self._tv.sendKey("Previous") self._update_soon(DELAY_ACTION_DEFAULT) def media_next_track(self): """Send fast forward command.""" self._tv.sendKey("Next") self._update_soon(DELAY_ACTION_DEFAULT) @property def media_channel(self): """Get current channel if it's a channel.""" if self.media_content_type == MEDIA_TYPE_CHANNEL: return self._channels.get(self._tv.channel_id) return None @property def media_title(self): """Title of current playing media.""" if self.media_content_type == MEDIA_TYPE_CHANNEL: return self._channels.get(self._tv.channel_id) return self._sources.get(self._tv.source_id) @property def media_content_type(self): """Return content type of playing media.""" if self._tv.source_id == "tv" or self._tv.source_id == "11": return MEDIA_TYPE_CHANNEL if self._tv.source_id is None and self._tv.channels: return MEDIA_TYPE_CHANNEL return None @property def media_content_id(self): """Content type of current playing media.""" if self.media_content_type == MEDIA_TYPE_CHANNEL: return self._channels.get(self._tv.channel_id) return None @property def device_state_attributes(self): """Return the state attributes.""" return {"channel_list": list(self._channels.values())} def play_media(self, media_type, media_id, **kwargs): """Play a piece of media.""" _LOGGER.debug("Call play media type <%s>, Id <%s>", media_type, media_id) if media_type == MEDIA_TYPE_CHANNEL: channel_id = _inverted(self._channels).get(media_id) if channel_id: self._tv.setChannel(channel_id) self._update_soon(DELAY_ACTION_DEFAULT) else: _LOGGER.error("Unable to find channel <%s>", media_id) else: _LOGGER.error("Unsupported media type <%s>", media_type) def update(self): """Get the latest data and update device state.""" self._tv.update() self._sources = { srcid: source["name"] or f"Source {srcid}" for srcid, source in (self._tv.sources or {}).items() } self._channels = { chid: channel["name"] for chid, channel in (self._tv.channels or {}).items() }
"""Get the device state. An exception means OFF state.""" if self._tv.on: return STATE_ON return STATE_OFF
data-editor.tsx
import * as React from "react"; import { assertNever, maybe } from "../common/support"; import { clamp } from "lodash-es"; import DataGridOverlayEditor from "../data-grid-overlay-editor/data-grid-overlay-editor"; import { EditableGridCell, GridCell, GridCellKind, GridDragEventArgs, GridKeyEventArgs, GridMouseEventArgs, GridSelection, isEditableGridCell, Rectangle, isReadWriteCell, InnerGridCell, InnerGridCellKind, CompactSelection, Slice, isInnerOnlyCell, ProvideEditorCallback, DrawCustomCellCallback, GridMouseCellEventArgs, GridMouseHeaderEventArgs, GridMouseGroupHeaderEventArgs, } from "../data-grid/data-grid-types"; import DataGridSearch, { DataGridSearchProps } from "../data-grid-search/data-grid-search"; import { browserIsOSX } from "../common/browser-detect"; import { OverlayImageEditorProps } from "../data-grid-overlay-editor/private/image-overlay-editor"; import { ThemeProvider, useTheme } from "@emotion/react"; import { getDataEditorTheme, Theme } from "../common/styles"; import { DataGridRef } from "../data-grid/data-grid"; import { useEventListener } from "../common/utils"; import { CellRenderers } from "../data-grid/cells"; import { isGroupEqual } from "../data-grid/data-grid-lib"; import { GroupRename } from "./group-rename"; interface MouseState { readonly previousSelection?: GridSelection; } type Props = Omit< DataGridSearchProps, | "canvasRef" | "cellXOffset" | "cellYOffset" | "className" | "disabledRows" | "drawCustomCell" | "enableGroups" | "firstColSticky" | "getCellContent" | "gridRef" | "headerHeight" | "groupHeaderHeight" | "lastRowSticky" | "lockColumns" | "onCellFocused" | "onKeyDown" | "onKeyUp" | "onMouseDown" | "onMouseUp" | "onMouseMove" | "freezeColumns" | "onSearchResultsChanged" | "onVisibleRegionChanged" | "rowHeight" | "verticalBorder" | "scrollRef" | "searchColOffset" | "selectedCell" | "selectedColumns" | "translateX" | "translateY" >; type ImageEditorType = React.ComponentType<OverlayImageEditorProps>; type ReplaceReturnType<T extends (...a: any) => any, TNewReturn> = (...a: Parameters<T>) => TNewReturn; type HeaderSelectionTrigger = "selection" | "drag" | "header" | "group"; interface PreventableEvent { preventDefault: () => void; } interface CellClickedEventArgs extends GridMouseCellEventArgs, PreventableEvent {} interface HeaderClickedEventArgs extends GridMouseHeaderEventArgs, PreventableEvent {} interface GroupHeaderClickedEventArgs extends GridMouseGroupHeaderEventArgs, PreventableEvent {} export interface DataEditorProps extends Props { readonly onDeleteRows?: (rows: readonly number[]) => void; readonly onCellEdited?: (cell: readonly [number, number], newValue: EditableGridCell) => void; readonly onRowAppended?: () => Promise<"top" | "bottom" | undefined> | void; readonly onHeaderClicked?: (colIndex: number, event: HeaderClickedEventArgs) => void; readonly onGroupHeaderClicked?: (colIndex: number, event: GroupHeaderClickedEventArgs) => void; readonly onGroupHeaderRenamed?: (groupName: string, newVal: string) => void; readonly onCellClicked?: (cell: readonly [number, number], event: CellClickedEventArgs) => void; readonly trailingRowOptions?: { readonly tint?: boolean; readonly hint?: string; readonly sticky?: boolean; }; readonly headerHeight?: number; readonly groupHeaderHeight?: number; readonly rowMarkers?: "checkbox" | "number" | "both" | "none"; readonly rowMarkerWidth?: number; readonly rowHeight?: DataGridSearchProps["rowHeight"]; readonly onMouseMove?: DataGridSearchProps["onMouseMove"]; readonly imageEditorOverride?: ImageEditorType; readonly markdownDivCreateNode?: (content: string) => DocumentFragment; readonly provideEditor?: ProvideEditorCallback<GridCell>; readonly onSelectedRowsChange?: (newRows: CompactSelection) => void; readonly selectedColumns?: DataGridSearchProps["selectedColumns"]; readonly onSelectedColumnsChange?: (newColumns: CompactSelection, trigger: HeaderSelectionTrigger) => void; /** * @deprecated Use drawCell instead. This will be removed in a future version. */ readonly drawCustomCell?: ( ctx: CanvasRenderingContext2D, cell: GridCell, theme: Theme, rect: Rectangle, hoverAmount: number ) => boolean; readonly drawCell?: DrawCustomCellCallback; readonly gridSelection?: GridSelection; readonly onGridSelectionChange?: (newSelection: GridSelection | undefined) => void; readonly onVisibleRegionChanged?: (range: Rectangle, tx?: number, ty?: number) => void; readonly getCellContent: ReplaceReturnType<DataGridSearchProps["getCellContent"], GridCell>; readonly rowSelectionMode?: "auto" | "multi"; readonly enableDownfill?: boolean; readonly freezeColumns?: DataGridSearchProps["freezeColumns"]; readonly verticalBorder?: DataGridSearchProps["verticalBorder"] | boolean; readonly onPaste?: | ((target: readonly [number, number], values: readonly (readonly string[])[]) => boolean) | boolean; } export interface DataEditorRef { updateCells: DataGridRef["damage"]; getBounds: DataGridRef["getBounds"]; } const loadingCell: GridCell = { kind: GridCellKind.Loading, allowOverlay: false, }; const DataEditorImpl: React.ForwardRefRenderFunction<DataEditorRef, DataEditorProps> = (p, forwardedRef) => { const [gridSelectionInner, setGridSelectionInner] = React.useState<GridSelection>(); const [selectedColumnsInner, setSelectedColumnsInner] = React.useState<CompactSelection>(CompactSelection.empty()); const [selectedRowsInner, setSelectedRowsInner] = React.useState(CompactSelection.empty()); const [overlay, setOverlay] = React.useState<{ target: Rectangle; content: GridCell; cell: readonly [number, number]; highlight: boolean; forceEditMode: boolean; }>(); const canvasRef = React.useRef<HTMLCanvasElement | null>(null); const mouseState = React.useRef<MouseState>(); const scrollRef = React.useRef<HTMLDivElement | null>(null); const scrollTimer = React.useRef<number>(); const lastSent = React.useRef<[number, number]>(); const { isDraggable = false, getCellsForSelection, rowMarkers = "none", rowHeight = 34, headerHeight = 36, rowMarkerWidth: rowMarkerWidthRaw, imageEditorOverride, markdownDivCreateNode, } = p; const { columns, rows, getCellContent, onCellClicked, onHeaderClicked, onGroupHeaderClicked, onGroupHeaderRenamed, onCellEdited, enableDownfill = false, onRowAppended, onColumnMoved, drawCell, drawCustomCell, onDeleteRows, onDragStart, onMouseMove, onPaste, groupHeaderHeight = headerHeight, freezeColumns = 0, rowSelectionMode = "auto", onHeaderMenuClick, getGroupDetails, onItemHovered, onVisibleRegionChanged, selectedColumns: selectedColumnsOuter, onSelectedColumnsChange: setSelectedColumnsOuter, selectedRows: selectedRowsOuter, onSelectedRowsChange: setSelectedRowsOuter, gridSelection: gridSelectionOuter, onGridSelectionChange, provideEditor, trailingRowOptions, verticalBorder, ...rest } = p; const rowMarkerWidth = rowMarkerWidthRaw ?? (rows > 10000 ? 48 : rows > 1000 ? 44 : rows > 100 ? 36 : 32); const hasRowMarkers = rowMarkers !== "none"; const rowMarkerOffset = hasRowMarkers ? 1 : 0; const showTrailingBlankRow = onRowAppended !== undefined; const lastRowSticky = trailingRowOptions?.sticky === true; const gridSelectionOuterMangled: GridSelection | undefined = React.useMemo(() => { return gridSelectionOuter === undefined ? undefined : { cell: [gridSelectionOuter.cell[0] + rowMarkerOffset, gridSelectionOuter.cell[1]], range: { ...gridSelectionOuter.range, x: gridSelectionOuter.range.x + rowMarkerOffset, }, }; }, [gridSelectionOuter, rowMarkerOffset]); const gridSelection = gridSelectionOuterMangled ?? gridSelectionInner; const setGridSelection = React.useCallback( (newVal: GridSelection | undefined) => { if (onGridSelectionChange !== undefined) { if (newVal === undefined) { onGridSelectionChange(undefined); } else { onGridSelectionChange({ cell: [newVal.cell[0] - rowMarkerOffset, newVal.cell[1]], range: { ...newVal.range, x: newVal.range.x - rowMarkerOffset, }, }); } } else { setGridSelectionInner(newVal); } }, [onGridSelectionChange, rowMarkerOffset] ); const selectedRows = selectedRowsOuter ?? selectedRowsInner; const setSelectedRows = setSelectedRowsOuter ?? setSelectedRowsInner; const mangledOuterCols = selectedColumnsOuter?.offset(rowMarkerOffset); const selectedColumns = mangledOuterCols ?? selectedColumnsInner; const setSelectedColumns = React.useCallback( (newColumns: CompactSelection, trigger: HeaderSelectionTrigger) => { if (setSelectedColumnsOuter !== undefined) { setSelectedColumnsOuter?.(newColumns.offset(-rowMarkerOffset), trigger); } else { setSelectedColumnsInner(newColumns); } }, [rowMarkerOffset, setSelectedColumnsOuter] ); const enableGroups = React.useMemo(() => { return columns.some(c => c.group !== undefined); }, [columns]); const totalHeaderHeight = enableGroups ? headerHeight + groupHeaderHeight : headerHeight; const [visibleRegion, setVisibleRegion] = React.useState<Rectangle & { tx?: number; ty?: number }>({ x: 0, y: 0, width: 1, height: 1, }); const cellXOffset = visibleRegion.x + rowMarkerOffset; const cellYOffset = visibleRegion.y; const gridRef = React.useRef<DataGridRef | null>(null); React.useImperativeHandle( forwardedRef, () => ({ updateCells: (...args) => gridRef.current?.damage(...args), getBounds: (...args) => gridRef.current?.getBounds(...args), }), [] ); const focus = React.useCallback((immediate?: boolean) => { if (immediate === true) { gridRef.current?.focus(); } else { window.requestAnimationFrame(() => { gridRef.current?.focus(); }); } }, []); const mangledRows = showTrailingBlankRow ? rows + 1 : rows; const mangledOnCellEdited = React.useCallback( (cell: readonly [number, number], newValue: EditableGridCell) => { onCellEdited?.([cell[0] - rowMarkerOffset, cell[1]], newValue); }, [onCellEdited, rowMarkerOffset] ); const mangledCols = React.useMemo(() => { if (rowMarkers === "none") return columns; return [ { title: "", width: rowMarkerWidth, icon: undefined, hasMenu: false, style: "normal" as const, }, ...columns, ]; }, [columns, rowMarkerWidth, rowMarkers]); const getMangedCellContent = React.useCallback( ([col, row]: readonly [number, number]): InnerGridCell => { const isTrailing = showTrailingBlankRow && row === mangledRows - 1; const isRowMarkerCol = col === 0 && hasRowMarkers; if (isRowMarkerCol) { if (isTrailing) { return loadingCell; } return { kind: InnerGridCellKind.Marker, allowOverlay: false, checked: selectedRows.hasIndex(row), markerKind: rowMarkers, row, }; } else if (isTrailing) { //If the grid is empty, we will return text const isFirst = col === rowMarkerOffset; const display = isFirst ? trailingRowOptions?.hint ?? "" : ""; return { kind: InnerGridCellKind.NewRow, hint: display, isFirst, allowOverlay: false, }; } else { return getCellContent([col - rowMarkerOffset, row]); } }, [ showTrailingBlankRow, mangledRows, hasRowMarkers, selectedRows, rowMarkers, rowMarkerOffset, trailingRowOptions?.hint, getCellContent, ] ); const reselect = React.useCallback( (bounds: Rectangle, initialValue?: string) => { if (gridSelection === undefined) return; const [col, row] = gridSelection.cell; const c = getMangedCellContent([col, row]); if (c.kind !== GridCellKind.Boolean && c.allowOverlay) { let content = c; if (initialValue !== undefined) { switch (content.kind) { case GridCellKind.Text: content = { ...content, data: initialValue, }; break; case GridCellKind.Number: content = { ...content, data: maybe(() => Number.parseFloat(initialValue), 0), }; break; case GridCellKind.Markdown: case GridCellKind.Uri: content = { ...content, data: initialValue, }; break; } } setOverlay({ target: bounds, content, cell: [col, row], highlight: initialValue === undefined, forceEditMode: initialValue !== undefined, }); } }, [getMangedCellContent, gridSelection] ); const focusOnRowFromTrailingBlankRow = React.useCallback( (col: number, row: number) => { const bounds = gridRef.current?.getBounds(col, row); if (bounds === undefined || scrollRef.current === null) { return; } let content = getMangedCellContent([col, row]); if (!content.allowOverlay) { return; } switch (content.kind) { case GridCellKind.Text: content = { ...content, data: "", }; break; case GridCellKind.Number: content = { ...content, data: undefined, }; break; case GridCellKind.Markdown: case GridCellKind.Uri: content = { ...content, data: "", }; break; } setOverlay({ target: bounds, content, highlight: true, cell: [col, row], forceEditMode: true, }); }, [getMangedCellContent] ); const focusCallback = React.useRef(focusOnRowFromTrailingBlankRow); const getCellContentRef = React.useRef(getCellContent); const rowsRef = React.useRef(rows); focusCallback.current = focusOnRowFromTrailingBlankRow; getCellContentRef.current = getCellContent; rowsRef.current = rows; const appendRow = React.useCallback( async (col: number) => { // FIXME: Maybe this should optionally return a promise that we can await? const appendResult = onRowAppended?.(); let bottom = true; if (appendResult !== undefined) { const r = await appendResult; if (r === "top") bottom = false; } let backoff = 0; const doFocus = () => { if (rowsRef.current <= rows) { if (backoff < 500) { window.setTimeout(doFocus, backoff); } backoff = 50 + backoff * 2; return; } const row = bottom ? rows : 0; scrollRef.current?.scrollBy(0, (bottom ? 1 : -1) * scrollRef.current.scrollHeight + 1000); setGridSelection({ cell: [col, row], range: { x: col, y: row, width: 1, height: 1, }, }); const cell = getCellContentRef.current([col - rowMarkerOffset, row]); if (cell.allowOverlay && isReadWriteCell(cell) && cell.readonly !== true) { // wait for scroll to have a chance to process window.setTimeout(() => { focusCallback.current(col, row); }, 0); } }; // Queue up to allow the consumer to react to the event and let us check if they did doFocus(); }, [onRowAppended, rowMarkerOffset, rows, setGridSelection] ); const lastSelectedRowRef = React.useRef<number>(); const lastSelectedColRef = React.useRef<number>(); const onMouseDown = React.useCallback( (args: GridMouseEventArgs) => { mouseState.current = { previousSelection: gridSelection, }; const isMultiKey = browserIsOSX.value ? args.metaKey : args.ctrlKey; if (args.kind === "cell") { lastSelectedColRef.current = undefined; const [col, row] = args.location; if (col === 0 && hasRowMarkers) { if ((showTrailingBlankRow === true && row === rows) || rowMarkers === "number") return; setGridSelection(undefined); setOverlay(undefined); focus(); setSelectedColumns(CompactSelection.empty(), "selection"); const isSelected = selectedRows.hasIndex(row); const lastHighlighted = lastSelectedRowRef.current; if (args.shiftKey && lastHighlighted !== undefined && selectedRows.hasIndex(lastHighlighted)) { const newSlice: Slice = [Math.min(lastHighlighted, row), Math.max(lastHighlighted, row) + 1]; if (isMultiKey || rowSelectionMode === "multi") { setSelectedRows(selectedRows.add(newSlice)); } else { setSelectedRows(CompactSelection.fromSingleSelection(newSlice)); } } else if (isMultiKey || args.isTouch || rowSelectionMode === "multi") { if (isSelected) { setSelectedRows(selectedRows.remove(row)); } else { setSelectedRows(selectedRows.add(row)); lastSelectedRowRef.current = row; } } else if (isSelected && selectedRows.length === 1) { setSelectedRows(CompactSelection.empty()); } else { setSelectedRows(CompactSelection.fromSingleSelection(row)); lastSelectedRowRef.current = row; } } else if (col >= rowMarkerOffset && showTrailingBlankRow && row === rows) { void appendRow(col); } else { if (gridSelection?.cell[0] !== col || gridSelection.cell[1] !== row) { const isLastStickyRow = lastRowSticky && row === rows; const startedFromLastSticky = lastRowSticky && gridSelection !== undefined && gridSelection.cell[1] === rows; if (args.shiftKey && gridSelection !== undefined && !startedFromLastSticky) { if (isLastStickyRow) { // If we're making a selection and shift click in to the last sticky row, // just drop the event. Don't kill the selection. return; } const [sCol, sRow] = gridSelection.cell; const left = Math.min(col, sCol); const right = Math.max(col, sCol); const top = Math.min(row, sRow); const bottom = Math.max(row, sRow); setGridSelection({ ...gridSelection, range: { x: left, y: top, width: right - left + 1, height: bottom - top + 1, }, }); lastSelectedRowRef.current = undefined; focus(); } else { setGridSelection({ cell: [col, row], range: { x: col, y: row, width: 1, height: 1 } }); setSelectedColumns(CompactSelection.empty(), "selection"); setSelectedRows(CompactSelection.empty()); lastSelectedRowRef.current = undefined; setOverlay(undefined); focus(); } } } } else if (args.kind === "header") { const [col] = args.location; setGridSelection(undefined); setOverlay(undefined); if (hasRowMarkers && col === 0) { lastSelectedRowRef.current = undefined; lastSelectedColRef.current = undefined; if (selectedRows.length !== rows) { setSelectedRows(CompactSelection.fromSingleSelection([0, rows])); } else { setSelectedRows(CompactSelection.empty()); } focus(); } else { const lastCol = lastSelectedColRef.current; if (args.shiftKey && lastCol !== undefined && selectedColumns.hasIndex(lastCol)) { const newSlice: Slice = [Math.min(lastCol, col), Math.max(lastCol, col) + 1]; if (isMultiKey) { setSelectedColumns(selectedColumns.add(newSlice), "header"); } else { setSelectedColumns(CompactSelection.fromSingleSelection(newSlice), "header"); } } else if (isMultiKey) { if (selectedColumns.hasIndex(col)) { setSelectedColumns(selectedColumns.remove(col), "header"); } else { setSelectedColumns(selectedColumns.add(col), "header"); } lastSelectedColRef.current = col; } else { setSelectedColumns(CompactSelection.fromSingleSelection(col), "header"); lastSelectedColRef.current = col; } setSelectedRows(CompactSelection.empty()); lastSelectedRowRef.current = undefined; focus(); } } else if (args.kind === "out-of-bounds") { setGridSelection(undefined); setOverlay(undefined); focus(); setSelectedColumns(CompactSelection.empty(), "selection"); setSelectedRows(CompactSelection.empty()); lastSelectedRowRef.current = undefined; lastSelectedColRef.current = undefined; } else if (args.kind === "group-header") { const [col] = args.location; if (col < rowMarkerOffset) return; const needle = mangledCols[col]; let start = col; let end = col; for (let i = col - 1; i >= rowMarkerOffset; i--) { if (!isGroupEqual(needle.group, mangledCols[i].group)) break; start--; } for (let i = col + 1; i < mangledCols.length; i++) { if (!isGroupEqual(needle.group, mangledCols[i].group)) break; end++; } setSelectedRows(CompactSelection.empty()); setGridSelection(undefined); focus(); if (isMultiKey) { if (selectedColumns.hasAll([start, end + 1])) { let newVal = selectedColumns; for (let index = start; index <= end; index++) { newVal = newVal.remove(index); } setSelectedColumns(newVal, "group"); } else { setSelectedColumns(selectedColumns.add([start, end + 1]), "group"); } } else { setSelectedColumns(CompactSelection.fromSingleSelection([start, end + 1]), "group"); } } }, [ gridSelection, hasRowMarkers, rowMarkerOffset, showTrailingBlankRow, rows, rowMarkers, setGridSelection, focus, setSelectedColumns, selectedRows, rowSelectionMode, setSelectedRows, appendRow, lastRowSticky, selectedColumns, mangledCols, ] ); const [renameGroup, setRenameGroup] = React.useState<{ group: string; bounds: Rectangle; }>(); const onMouseUp = React.useCallback( (args: GridMouseEventArgs, isOutside: boolean) => { const mouse = mouseState.current; mouseState.current = undefined; if (isOutside) return; let prevented = false; const preventDefault = () => { prevented = true; }; if (scrollTimer.current !== undefined) { window.clearInterval(scrollTimer.current); } if (args.kind === "header") { onHeaderClicked?.(args.location[0] - rowMarkerOffset, { ...args, preventDefault }); } if (args.kind === "group-header") { onGroupHeaderClicked?.(args.location[0] - rowMarkerOffset, { ...args, preventDefault }); } if (args.kind !== "cell") { return; } onCellClicked?.([args.location[0] - rowMarkerOffset, args.location[1]], { ...args, preventDefault }); if (gridSelection !== undefined && mouse?.previousSelection?.cell !== undefined && !prevented) { const [col, row] = args.location; const [selectedCol, selectedRow] = gridSelection.cell; const [prevCol, prevRow] = mouse.previousSelection.cell; const c = getMangedCellContent([col, row]); const r = c.kind === GridCellKind.Custom ? undefined : CellRenderers[c.kind]; if (r !== undefined && r.onClick !== undefined) { const newVal = r.onClick(c, args.localEventX, args.localEventY, args.bounds); if (newVal !== undefined && !isInnerOnlyCell(newVal) && isEditableGridCell(newVal)) { mangledOnCellEdited(args.location, newVal); gridRef.current?.damage([ { cell: args.location, }, ]); } } if (col === selectedCol && col === prevCol && row === selectedRow && row === prevRow) { reselect(args.bounds); } } }, [ getMangedCellContent, gridSelection, mangledOnCellEdited, onCellClicked, onGroupHeaderClicked, onHeaderClicked, reselect, rowMarkerOffset, ] ); const onHeaderMenuClickInner = React.useCallback( (col: number, screenPosition: Rectangle) => { onHeaderMenuClick?.(col - rowMarkerOffset, screenPosition); }, [onHeaderMenuClick, rowMarkerOffset] ); const onVisibleRegionChangedImpl = React.useCallback( (region: Rectangle, tx?: number, ty?: number) => { const newRegion = { ...region, x: region.x - rowMarkerOffset, height: showTrailingBlankRow && region.y + region.height >= rows ? region.height - 1 : region.height, tx, ty, }; setVisibleRegion(newRegion); onVisibleRegionChanged?.(newRegion, tx, ty); }, [onVisibleRegionChanged, rowMarkerOffset, rows, showTrailingBlankRow] ); const onColumnMovedImpl = React.useCallback( (startIndex: number, endIndex: number) => { onColumnMoved?.(startIndex - rowMarkerOffset, endIndex - rowMarkerOffset); setSelectedColumns(CompactSelection.fromSingleSelection(endIndex), "drag"); }, [onColumnMoved, rowMarkerOffset, setSelectedColumns] ); const onDragStartImpl = React.useCallback( (args: GridDragEventArgs) => { onDragStart?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any, }); }, [onDragStart, rowMarkerOffset] ); const onMouseMoveImpl = React.useCallback( (args: GridMouseEventArgs) => { const a: GridMouseEventArgs = { ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any, }; onMouseMove?.(a); }, [onMouseMove, rowMarkerOffset] ); const onItemHoveredImpl = React.useCallback( (args: GridMouseEventArgs) => { if (mouseState.current !== undefined && gridSelection !== undefined && !isDraggable) { const [selectedCol, selectedRow] = gridSelection.cell; // eslint-disable-next-line prefer-const let [col, row] = args.location; const landedOnLastStickyRow = lastRowSticky && row === rows; const startedFromLastStickyRow = lastRowSticky && selectedRow === rows; if (landedOnLastStickyRow || startedFromLastStickyRow) return; if (col === 0 && hasRowMarkers) { col = 1; } const deltaX = col - selectedCol; const deltaY = (row ?? 0) - selectedRow; const newRange: Rectangle = { x: deltaX >= 0 ? selectedCol : col, y: deltaY >= 0 ? selectedRow : row ?? 0, width: Math.abs(deltaX) + 1, height: Math.abs(deltaY) + 1, }; setGridSelection({ ...gridSelection, range: newRange, }); if (args.kind === "out-of-bounds" && scrollRef.current !== null) { const [horizontal, vertical] = args.direction; let scrollX = 0; let scrollY = 0; if (horizontal === -1) { scrollX = columns[columns.length - 1].width; } else if (horizontal === 1) { scrollX = -columns[0].width; } if (vertical !== 0) { if (typeof rowHeight === "number") { scrollY = rowHeight * vertical; } else { scrollY = rowHeight(row ?? 0) * vertical; } } if (scrollTimer.current !== undefined) { window.clearInterval(scrollTimer.current); } scrollTimer.current = window.setInterval(() => { scrollRef.current?.scrollBy(-100 * horizontal, scrollY); }, 200); scrollRef.current.scrollBy(scrollX, scrollY); } else { if (scrollTimer.current !== undefined) { window.clearInterval(scrollTimer.current); } } } onItemHovered?.({ ...args, location: [args.location[0] - rowMarkerOffset, args.location[1]] as any }); }, [ gridSelection, isDraggable, onItemHovered, rowMarkerOffset, lastRowSticky, rows, hasRowMarkers, setGridSelection, columns, rowHeight, ] ); const copyToClipboard = React.useCallback((cells: readonly (readonly GridCell[])[]) => { function escape(str: string): string { if (/\n|"|\t/.test(str)) { str = `"${str.replace(/"/g, `""`)}"`; } return str; } const formatCell = (cell: GridCell) => { switch (cell.kind) { case GridCellKind.Text: case GridCellKind.Number: return escape(cell.displayData); case GridCellKind.Markdown: case GridCellKind.RowID: case GridCellKind.Uri: return escape(cell.data); case GridCellKind.Image: case GridCellKind.Bubble: return cell.data.reduce((pv, cv) => `${escape(pv)},${escape(cv)}`); case GridCellKind.Boolean: return cell.data ? "TRUE" : "FALSE"; case GridCellKind.Loading: return "#LOADING"; case GridCellKind.Protected: return "************"; case GridCellKind.Drilldown: return cell.data.map(i => i.text).reduce((pv, cv) => `${escape(pv)},${escape(cv)}`); case GridCellKind.Custom: return escape(cell.copyData); default: assertNever(cell); } }; const str = cells.map(row => row.map(formatCell).join("\t")).join("\n"); void window.navigator.clipboard.writeText(str); }, []); const scrollTo = React.useCallback( (col: number, row: number, dir: "horizontal" | "vertical" | "both" = "both") => { if (scrollRef.current !== null) { const grid = gridRef.current; const canvas = canvasRef.current; if (grid !== null && canvas !== null) { const bounds = grid.getBounds(col, row); const scrollBounds = canvas.getBoundingClientRect(); if (bounds !== undefined) { let scrollX = 0; let scrollY = 0; const sLeft = scrollBounds.left + rowMarkerOffset * rowMarkerWidth; const sRight = scrollBounds.right; const sTop = scrollBounds.top + totalHeaderHeight; let trailingRowHeight = 0; if (lastRowSticky) { trailingRowHeight = typeof rowHeight === "number" ? rowHeight : rowHeight(rows); } const sBottom = scrollBounds.bottom - trailingRowHeight; if (sLeft > bounds.x) { scrollX = bounds.x - sLeft; } else if (sRight < bounds.x + bounds.width) { scrollX = bounds.x + bounds.width - sRight; } if (sTop > bounds.y) { scrollY = bounds.y - sTop; } else if (sBottom < bounds.y + bounds.height) { scrollY = bounds.y + bounds.height - sBottom; } if (dir === "vertical") { scrollX = 0; } else if (dir === "horizontal") { scrollY = 0; } if (scrollX !== 0 || scrollY !== 0) { scrollRef.current.scrollTo( scrollX + scrollRef.current.scrollLeft, scrollY + scrollRef.current.scrollTop ); } } } } }, [totalHeaderHeight, lastRowSticky, rowHeight, rowMarkerOffset, rowMarkerWidth, rows] ); const adjustSelection = React.useCallback( (direction: [number, number]) => { if (gridSelection === undefined) return; const [x, y] = direction; const [col, row] = gridSelection.cell; const oldRange = gridSelection.range; let left = oldRange?.x ?? col; let top = oldRange?.y ?? row; let width = oldRange?.width ?? 1; let height = oldRange?.height ?? 1; const topDiff = top - row; const leftDiff = left - col; let isTop = topDiff === 0; if (y < 0 && height === 1) isTop = false; const heightDiff = isTop ? y : y * -1; let isLeft = leftDiff === 0; if (x < 0 && width === 1) isLeft = false; const widthDiff = isLeft ? x : x * -1; if (isTop) { const maxHeight = rows - top; height += heightDiff; height = Math.min(maxHeight, height); scrollTo(0, top + height - 1, "vertical"); } else { top -= heightDiff; height = Math.abs(top - row) + 1; scrollTo(0, top, "vertical"); } if (isLeft) { width += widthDiff; scrollTo(left + width - 1, 0, "horizontal"); } else { left -= widthDiff; //Don't let it select the marker column left = Math.max(rowMarkerOffset, left); width = Math.abs(left - col) + 1; scrollTo(left, 0, "horizontal"); } setGridSelection({ ...gridSelection, range: { x: left, y: top, width: width, height: height, }, }); }, [gridSelection, rowMarkerOffset, rows, scrollTo, setGridSelection] ); const updateSelectedCell = React.useCallback( (col: number, row: number, fromEditingTrailingRow: boolean = false): boolean => { const rowMax = mangledRows - (fromEditingTrailingRow ? 0 : 1); col = clamp(rowMarkerOffset, columns.length - 1 + rowMarkerOffset, col); row = clamp(0, rowMax, row); if (col === gridSelection?.cell[0] && row === gridSelection?.cell[1]) return false; setGridSelection({ cell: [col, row], range: { x: col, y: row, width: 1, height: 1 } }); if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) { lastSent.current = undefined; } scrollTo(col, row); return true; }, [mangledRows, rowMarkerOffset, columns.length, gridSelection?.cell, setGridSelection, scrollTo] ); const onFinishEditing = React.useCallback( (newValue: GridCell | undefined, movement: readonly [-1 | 0 | 1, -1 | 0 | 1]) => { if (overlay?.cell !== undefined && newValue !== undefined) { // Fixme, this cast is dangerous mangledOnCellEdited?.(overlay.cell, newValue as EditableGridCell); window.requestAnimationFrame(() => { gridRef.current?.damage([ { cell: overlay.cell, }, ]); }); } focus(true); setOverlay(undefined); const [movX, movY] = movement; if (gridSelection !== undefined && (movX !== 0 || movY !== 0)) { const isEditingTrailingRow = gridSelection.cell[1] === mangledRows - 1 && newValue !== undefined; updateSelectedCell(gridSelection.cell[0] + movX, gridSelection.cell[1] + movY, isEditingTrailingRow); } }, [overlay?.cell, focus, gridSelection, mangledOnCellEdited, mangledRows, updateSelectedCell] ); const [selCol, selRow] = gridSelection?.cell ?? []; const onCellFocused = React.useCallback( (cell: readonly [number, number]) => { if (selCol === cell[0] && selRow === cell[1]) return; setGridSelection({ cell, range: { x: cell[0], y: cell[1], width: 1, height: 1 }, }); setSelectedRows(CompactSelection.empty()); }, [selCol, selRow, setGridSelection, setSelectedRows] ); const onKeyDown = React.useCallback( (event: GridKeyEventArgs) => { const fn = async () => { const overlayOpen = overlay !== undefined; const shiftKey = event.shiftKey; const isOSX = browserIsOSX.value; const isPrimaryKey = isOSX ? event.metaKey : event.ctrlKey; const isDeleteKey = event.key === "Delete" || (isOSX && event.key === "Backspace"); if (event.key === "Escape") { if (overlayOpen) { setOverlay(undefined); return; } setGridSelection(undefined); setSelectedRows(CompactSelection.empty()); setSelectedColumns(CompactSelection.empty(), "selection"); return; } if (isDeleteKey && selectedRows.length !== 0 && gridSelection === undefined) { event.cancel(); focus(); onDeleteRows?.(Array.from(selectedRows)); setSelectedRows(CompactSelection.empty()); return; } function deleteRange(range: Rectangle) { focus(); const damaged: [number, number][] = []; for (let x = range.x; x < range.x + range.width; x++) { for (let y = range.y; y < range.y + range.height; y++) { const cellValue = getCellContent([x - rowMarkerOffset, y]); if ( (isEditableGridCell(cellValue) && cellValue.allowOverlay) || cellValue.kind === GridCellKind.Boolean ) { const r = CellRenderers[cellValue.kind]; const newVal = r.onDelete?.(cellValue); if (newVal !== undefined) { mangledOnCellEdited([x, y], newVal as typeof cellValue); damaged.push([x, y]); } } } } gridRef.current?.damage(damaged.map(x => ({ cell: x }))); } if (isDeleteKey && selectedColumns.length > 0 && gridSelection === undefined) { event.cancel(); for (const col of selectedColumns) { deleteRange({ x: col, y: 0, width: 1, height: rows, }); } return; } if (gridSelection === undefined) return; let [col, row] = gridSelection.cell; if (event.key === "Enter" && event.bounds !== undefined) { if (overlayOpen) { setOverlay(undefined); row++; } else if (row === rows && showTrailingBlankRow) { window.setTimeout(() => { void appendRow(col); }, 0); } else { reselect(event.bounds); event.cancel(); } } else if (event.keyCode === 68 && isPrimaryKey && gridSelection.range.height > 1 && enableDownfill) { // ctrl/cmd + d const damage: (readonly [number, number])[] = []; const r = gridSelection.range; for (let x = 0; x < r.width; x++) { const fillCol = x + r.x; const fillVal = getMangedCellContent([fillCol, r.y]); if (isInnerOnlyCell(fillVal) || !isEditableGridCell(fillVal)) continue; for (let y = 1; y < r.height; y++) { const fillRow = y + r.y; const target = [fillCol, fillRow] as const; damage.push(target); mangledOnCellEdited?.(target, { ...fillVal, }); } } gridRef.current?.damage( damage.map(c => ({ cell: c, })) ); event.cancel(); } else if (event.key === "ArrowDown") { setOverlay(undefined); if (shiftKey) { adjustSelection([0, isPrimaryKey ? Number.MAX_SAFE_INTEGER : 1]); } else { row += isPrimaryKey ? Number.MAX_SAFE_INTEGER : 1; } } else if (event.key === "ArrowUp") { setOverlay(undefined); if (shiftKey) { adjustSelection([0, isPrimaryKey ? Number.MIN_SAFE_INTEGER : -1]); } else { row += isPrimaryKey ? Number.MIN_SAFE_INTEGER : -1; } } else if (event.key === "ArrowRight") { setOverlay(undefined); if (shiftKey) { adjustSelection([isPrimaryKey ? Number.MAX_SAFE_INTEGER : 1, 0]); } else { col += isPrimaryKey ? Number.MAX_SAFE_INTEGER : 1; } } else if (event.key === "ArrowLeft") { setOverlay(undefined); if (shiftKey) { adjustSelection([isPrimaryKey ? Number.MIN_SAFE_INTEGER : -1, 0]); } else { col += isPrimaryKey ? Number.MIN_SAFE_INTEGER : -1; } } else if (event.key === "Tab") { setOverlay(undefined); if (shiftKey) { col--; } else { col++; } } else if (isDeleteKey) { event.cancel(); const range = gridSelection.range; deleteRange(range); } else if ( !event.metaKey && !event.ctrlKey && String.fromCharCode(event.keyCode).match(/(\w|\s)/g) && event.bounds !== undefined && isReadWriteCell(getCellContent([col - rowMarkerOffset, Math.max(0, row - 1)])) ) { if ( (!lastRowSticky || row !== rows) && (visibleRegion.y > row || row > visibleRegion.y + visibleRegion.height || visibleRegion.x > col || col > visibleRegion.x + visibleRegion.width) ) { return; } let key = String.fromCharCode(event.keyCode); if (!event.shiftKey) { key = key.toLowerCase(); } reselect(event.bounds, key); event.cancel(); } const moved = updateSelectedCell(col, row); if (moved) { event.cancel(); } }; void fn(); }, [ overlay, selectedRows, gridSelection, selectedColumns, enableDownfill, getCellContent, rowMarkerOffset, updateSelectedCell, setGridSelection, setSelectedRows, setSelectedColumns, focus, onDeleteRows, mangledOnCellEdited, rows, showTrailingBlankRow, appendRow, reselect, getMangedCellContent, adjustSelection, lastRowSticky, visibleRegion.y, visibleRegion.height, visibleRegion.x, visibleRegion.width, ] ); function unquote(str: string): string[][] { function descape(s: string): string { if (s.startsWith('"') && s.endsWith('"')) { s = s.slice(1, -1).replace(/""/g, '"'); } return s; } const enum State { None, inString, inStringPostQuote, } const result: string[][] = []; let current: string[] = []; let start = 0; let state = State.None; str = str.trim().replace(/\r\n/g, "\n"); let index = 0; for (const char of str) { switch (state) { case State.None: if (char === "\t" || char === "\n") { current.push(str.slice(start, index)); start = index + 1; if (char === "\n") { result.push(current); current = []; } } else if (char === `"`) { state = State.inString; } break; case State.inString: if (char === `"`) { state = State.inStringPostQuote; } break; case State.inStringPostQuote: if (char === '"') { state = State.inString; } else if (char === "\t" || char === "\n") { current.push(descape(str.slice(start, index))); start = index + 1; if (char === "\n") { result.push(current); current = []; } state = State.None; } else { state = State.None; } break; } index++; } if (start < str.length) { current.push(descape(str.slice(start, str.length))); } result.push(current); return result; } useEventListener( "paste", React.useCallback(async () => { function pasteToCell(inner: InnerGridCell, target: readonly [number, number], toPaste: string): boolean { if (!isInnerOnlyCell(inner) && isReadWriteCell(inner) && inner.readonly !== true) { switch (inner.kind) { case GridCellKind.Text: case GridCellKind.Markdown: case GridCellKind.Uri: { mangledOnCellEdited?.(target, { ...inner, data: toPaste, }); return true; } case GridCellKind.Number: { const newNumber = Number.parseFloat(toPaste); if (!Number.isNaN(newNumber)) { mangledOnCellEdited?.(target, { ...inner, data: newNumber, }); return true; } return false; } default: assertNever(inner); } } return false; } const focused = scrollRef.current?.contains(document.activeElement) === true || canvasRef.current?.contains(document.activeElement) === true; let target = gridSelection?.cell; if (target === undefined && selectedColumns.length === 1) { target = [selectedColumns.first() ?? 0, 0]; } if (target === undefined && selectedRows.length === 1) { target = [rowMarkerOffset, selectedRows.first() ?? 0]; } if (focused && target !== undefined) { const text = await navigator.clipboard.readText(); const [gridCol, gridRow] = target; if (onPaste === undefined) { const cellData = getMangedCellContent(target); pasteToCell(cellData, target, text); return; } const data = unquote(text); if (onPaste === false || (typeof onPaste === "function" && onPaste?.(target, data) !== true)) { return; } const damage: (readonly [number, number])[] = []; for (let row = 0; row < data.length; row++) { const dataRow = data[row]; if (row + gridRow >= rows) break; for (let col = 0; col < dataRow.length; col++) { const dataItem = dataRow[col]; const index = [col + gridCol, row + gridRow] as const; const cellData = getMangedCellContent(index); if (pasteToCell(cellData, index, dataItem)) { damage.push(index); } } } gridRef.current?.damage( damage.map(c => ({ cell: c, })) ); } }, [ getMangedCellContent, gridSelection, mangledOnCellEdited, onPaste, rowMarkerOffset, rows, selectedColumns, selectedRows, ]), window, false, true ); useEventListener( "copy", React.useCallback(() => { const focused = scrollRef.current?.contains(document.activeElement) === true || canvasRef.current?.contains(document.activeElement) === true; if (focused && getCellsForSelection) { if (gridSelection !== undefined) { const [col, row] = gridSelection.cell; if (gridSelection.range !== undefined && getCellsForSelection !== undefined) { copyToClipboard( getCellsForSelection({ ...gridSelection.range, x: gridSelection.range.x - rowMarkerOffset, }) ); } else { const cellValue = getCellContent([col - rowMarkerOffset, row]); copyToClipboard([[cellValue]]); } } else if (selectedRows !== undefined && selectedRows.length > 0) { const toCopy = Array.from(selectedRows); const cells = toCopy.map( rowIndex => getCellsForSelection({ x: 0, y: rowIndex, width: columns.length, height: 1, })[0] ); copyToClipboard(cells); } else if (selectedColumns.length >= 1) { const results: (readonly (readonly GridCell[])[])[] = []; for (const col of selectedColumns) { results.push( getCellsForSelection({ x: col - rowMarkerOffset, y: 0, width: 1, height: rows, }) ); } if (results.length === 1) { copyToClipboard(results[0]); } // FIXME: this is dumb const toCopy = results.reduce((pv, cv) => pv.map((row, index) => [...row, ...cv[index]])); copyToClipboard(toCopy); } } }, [ columns.length, copyToClipboard, getCellContent, getCellsForSelection, gridSelection, rowMarkerOffset, rows, selectedColumns, selectedRows, ]), window, true, false ); const onSearchResultsChanged = React.useCallback( (results: readonly (readonly [number, number])[], navIndex: number) => { if (results.length === 0 || navIndex === -1) return; const [col, row] = results[navIndex]; if (lastSent.current !== undefined && lastSent.current[0] === col && lastSent.current[1] === row) { return; } lastSent.current = [col, row]; updateSelectedCell(col, row); }, [updateSelectedCell] ); React.useEffect(() => {
const [col, row] = gridSelection.cell; // Check that the grid selection is in range before updating the selected cell const selectionColInRange = mangledCols[col]; if (selectionColInRange === undefined) return; updateSelectedCell(col, row); }, [mangledCols, rows, gridSelection, updateSelectedCell]); const disabledRows = React.useMemo(() => { if (showTrailingBlankRow === true && trailingRowOptions?.tint === true) { return CompactSelection.fromSingleSelection(mangledRows - 1); } return CompactSelection.empty(); }, [mangledRows, showTrailingBlankRow, trailingRowOptions?.tint]); const theme = useTheme(); const mergedTheme: Theme & typeof theme = React.useMemo(() => { return { ...getDataEditorTheme(), ...theme }; }, [theme]); const mangledVerticalBorder = React.useCallback( (col: number) => { return typeof verticalBorder === "boolean" ? verticalBorder : verticalBorder?.(col - rowMarkerOffset) ?? true; }, [rowMarkerOffset, verticalBorder] ); const mangledGetGroupDetails = React.useCallback<NonNullable<DataEditorProps["getGroupDetails"]>>( group => { let result = getGroupDetails?.(group) ?? { name: group }; if (onGroupHeaderRenamed !== undefined && group !== "") { result = { icon: result.icon, name: result.name, overrideTheme: result.overrideTheme, actions: [ ...(result.actions ?? []), { title: "Rename", icon: "renameIcon", onClick: e => setRenameGroup({ group: result.name, bounds: e.bounds, }), }, ], }; } return result; }, [getGroupDetails, onGroupHeaderRenamed] ); const drawCustomCellMangled: typeof drawCell = React.useMemo(() => { if (drawCell !== undefined) { return drawCell; } else if (drawCustomCell !== undefined) { return a => drawCustomCell(a.ctx, a.cell, a.theme, a.rect, a.hoverAmount); } return undefined; }, [drawCell, drawCustomCell]); const renameGroupNode = React.useMemo(() => { if (renameGroup === undefined || canvasRef.current === null) return null; const { bounds, group } = renameGroup; const canvasBounds = canvasRef.current.getBoundingClientRect(); return ( <GroupRename bounds={bounds} group={group} canvasBounds={canvasBounds} onClose={() => setRenameGroup(undefined)} onFinish={newVal => { setRenameGroup(undefined); onGroupHeaderRenamed?.(group, newVal); }} /> ); }, [onGroupHeaderRenamed, renameGroup]); const mangledFreezeColumns = Math.min(mangledCols.length, freezeColumns + (hasRowMarkers ? 1 : 0)); return ( <ThemeProvider theme={mergedTheme}> <DataGridSearch {...rest} enableGroups={enableGroups} canvasRef={canvasRef} cellXOffset={cellXOffset} cellYOffset={cellYOffset} columns={mangledCols} drawCustomCell={drawCustomCellMangled} disabledRows={disabledRows} freezeColumns={mangledFreezeColumns} lockColumns={rowMarkerOffset} getCellContent={getMangedCellContent} getGroupDetails={mangledGetGroupDetails} headerHeight={headerHeight} groupHeaderHeight={enableGroups ? groupHeaderHeight : 0} lastRowSticky={lastRowSticky} onCellFocused={onCellFocused} onColumnMoved={onColumnMoved === undefined ? undefined : onColumnMovedImpl} onDragStart={onDragStartImpl} onHeaderMenuClick={onHeaderMenuClickInner} onItemHovered={onItemHoveredImpl} onMouseMove={onMouseMoveImpl} onKeyDown={onKeyDown} onMouseDown={onMouseDown} onMouseUp={onMouseUp} onSearchResultsChanged={onSearchResultsChanged} onVisibleRegionChanged={onVisibleRegionChangedImpl} rowHeight={rowHeight} rows={mangledRows} scrollRef={scrollRef} searchColOffset={rowMarkerOffset} selectedCell={gridSelection} selectedColumns={selectedColumns} selectedRows={selectedRows} translateX={visibleRegion.tx} translateY={visibleRegion.ty} verticalBorder={mangledVerticalBorder} gridRef={gridRef} /> {renameGroupNode} {overlay !== undefined && ( <DataGridOverlayEditor {...overlay} className={p.experimental?.isSubGrid === true ? "click-outside-ignore" : undefined} provideEditor={provideEditor} imageEditorOverride={imageEditorOverride} onFinishEditing={onFinishEditing} markdownDivCreateNode={markdownDivCreateNode} /> )} </ThemeProvider> ); }; export const DataEditor = React.forwardRef(DataEditorImpl);
if (gridSelection === undefined) return;
ControlTableView.js
"use strict"; define( [ 'underscore', 'backbone', 'marionette', 'view/scenic/pages/base/TableView', 'view/scenic/pages/base/table/SourcesView', 'view/scenic/pages/control/ControlDestinationsView', 'view/scenic/pages/control/ControlMenusView', 'view/scenic/pages/control/ControlSourceView', 'view/scenic/pages/control/ControlPropertyView', 'view/scenic/pages/control/ControlConnectionView' ], function ( _, Backbone, Marionette, TableView, SourcesView, ControlDestinationsView, ControlMenus, ControlSourceView, ControlPropertyView, ControlConnectionView ) { /** * @constructor * @augments TableView */ var ControlTableView = TableView.extend( { className: 'table control', /** * Initialize */ initialize: function () { TableView.prototype.initialize.apply( this, arguments ); }, /**
* @private */ onBeforeShow: function () { this.showChildView( 'menus', new ControlMenus( { scenic: this.scenic, model: this.model } ) ); this.showChildView( 'sources', new SourcesView( { scenic: this.scenic, table: this.model, collection: this.model.getSourceCollection(), sourceView: ControlSourceView, sourceChildView: ControlPropertyView, connectionView: ControlConnectionView } ) ); this.showChildView( 'destinations', new ControlDestinationsView( { scenic: this.scenic, table: this.model, collection: this.model.getDestinationCollection() } ) ); } } ); return ControlTableView; } );
* Before Show Handler *
test_chassis.py
import logging import re import pytest import yaml from tests.common.helpers.assertions import pytest_assert from tests.common.helpers.platform_api import chassis from platform_api_test_base import PlatformApiTestBase logger = logging.getLogger(__name__) pytestmark = [ pytest.mark.disable_loganalyzer, # disable automatic loganalyzer pytest.mark.topology('any') ] REGEX_MAC_ADDRESS = r'^([0-9A-Fa-f]{2}:){5}([0-9A-Fa-f]{2})$' REGEX_SERIAL_NUMBER = r'^[A-Za-z0-9]+$' # Valid OCP ONIE TlvInfo EEPROM type codes as defined here: # https://opencomputeproject.github.io/onie/design-spec/hw_requirements.html ONIE_TLVINFO_TYPE_CODE_PRODUCT_NAME = '0x21' # Product Name ONIE_TLVINFO_TYPE_CODE_PART_NUMBER = '0x22' # Part Number ONIE_TLVINFO_TYPE_CODE_SERIAL_NUMBER = '0x23' # Serial Number ONIE_TLVINFO_TYPE_CODE_BASE_MAC_ADDR = '0x24' # Base MAC Address ONIE_TLVINFO_TYPE_CODE_MFR_DATE = '0x25' # Manufacture Date ONIE_TLVINFO_TYPE_CODE_DEVICE_VERSION = '0x26' # Device Version ONIE_TLVINFO_TYPE_CODE_LABEL_REVISION = '0x27' # Label Revision ONIE_TLVINFO_TYPE_CODE_PLATFORM_NAME = '0x28' # Platform Name ONIE_TLVINFO_TYPE_CODE_ONIE_VERSION = '0x29' # ONIE Version ONIE_TLVINFO_TYPE_CODE_NUM_MACS = '0x2A' # Number of MAC Addresses ONIE_TLVINFO_TYPE_CODE_MANUFACTURER = '0x2B' # Manufacturer ONIE_TLVINFO_TYPE_CODE_COUNTRY_CODE = '0x2C' # Country Code ONIE_TLVINFO_TYPE_CODE_VENDOR = '0x2D' # Vendor ONIE_TLVINFO_TYPE_CODE_DIAG_VERSION = '0x2E' # Diag Version ONIE_TLVINFO_TYPE_CODE_SERVICE_TAG = '0x2F' # Service Tag ONIE_TLVINFO_TYPE_CODE_VENDOR_EXT = '0xFD' # Vendor Extension ONIE_TLVINFO_TYPE_CODE_CRC32 = '0xFE' # CRC-32 class TestChassisApi(PlatformApiTestBase): ''' Platform API test cases for the Chassis class''' # # Functions to test methods inherited from DeviceBase class # def test_get_name(self, duthost, localhost, platform_api_conn): name = chassis.get_name(platform_api_conn) pytest_assert(name is not None, "Unable to retrieve chassis name") pytest_assert(isinstance(name, str), "Chassis name appears incorrect") def test_get_presence(self, duthost, localhost, platform_api_conn): presence = chassis.get_presence(platform_api_conn) pytest_assert(presence is not None, "Unable to retrieve chassis presence") pytest_assert(isinstance(presence, bool), "Chassis presence appears incorrect") # Chassis should always be present pytest_assert(presence is True, "Chassis is not present") def test_get_model(self, duthost, localhost, platform_api_conn): model = chassis.get_model(platform_api_conn) pytest_assert(model is not None, "Unable to retrieve chassis model") pytest_assert(isinstance(model, str), "Chassis model appears incorrect") def test_get_serial(self, duthost, localhost, platform_api_conn): serial = chassis.get_serial(platform_api_conn) pytest_assert(serial is not None, "Unable to retrieve chassis serial number") pytest_assert(isinstance(serial, str), "Chassis serial number appears incorrect") def test_get_status(self, duthost, localhost, platform_api_conn): status = chassis.get_status(platform_api_conn) pytest_assert(status is not None, "Unable to retrieve chassis status") pytest_assert(isinstance(status, bool), "Chassis status appears incorrect") # # Functions to test methods defined in ChassisBase class # def test_get_base_mac(self, duthost, localhost, platform_api_conn): # Ensure the base MAC address is sane base_mac = chassis.get_base_mac(platform_api_conn) pytest_assert(base_mac is not None, "Failed to retrieve base MAC address") pytest_assert(re.match(REGEX_MAC_ADDRESS, base_mac), "Base MAC address appears to be incorrect") if 'base_mac' in duthost.host.options['inventory_manager'].get_host(duthost.hostname).vars: expected_base_mac = duthost.host.options['inventory_manager'].get_host(duthost.hostname).vars['base_mac'] pytest_assert(base_mac == expected_base_mac, "Base MAC address is incorrect") else: logger.warning('Inventory file does not contain base MAC address for {}'.format(duthost.hostname)) def test_get_serial_number(self, duthost, localhost, platform_api_conn): # Ensure the serial number is sane # Note: It appears that when retrieving some variable-length fields, # the value is padded with trailing '\x00' bytes because the field # length is longer than the actual value, so we strip those bytes # here before comparing. We may want to change the EEPROM parsing # logic to ensure that trailing '\x00' bytes are removed when retreiving # a variable-length value. serial = chassis.get_serial_number(platform_api_conn).rstrip('\x00') pytest_assert(serial is not None, "Failed to retrieve serial number") pytest_assert(re.match(REGEX_SERIAL_NUMBER, serial), "Serial number appears to be incorrect") if 'serial' in duthost.host.options['inventory_manager'].get_host(duthost.hostname).vars: expected_serial = duthost.host.options['inventory_manager'].get_host(duthost.hostname).vars['serial'] pytest_assert(serial == expected_serial, "Serial number is incorrect") else: logger.warning('Inventory file does not contain serial number for {}'.format(duthost.hostname)) def test_get_system_eeprom_info(self, duthost, localhost, platform_api_conn): ''' Test that we can retrieve sane system EEPROM info from the DUT via the platform API ''' # OCP ONIE TlvInfo EEPROM type codes defined here: https://opencomputeproject.github.io/onie/design-spec/hw_requirements.html VALID_ONIE_TLVINFO_TYPE_CODES_LIST = [ ONIE_TLVINFO_TYPE_CODE_PRODUCT_NAME, ONIE_TLVINFO_TYPE_CODE_PART_NUMBER, ONIE_TLVINFO_TYPE_CODE_SERIAL_NUMBER, ONIE_TLVINFO_TYPE_CODE_BASE_MAC_ADDR, ONIE_TLVINFO_TYPE_CODE_MFR_DATE, ONIE_TLVINFO_TYPE_CODE_DEVICE_VERSION, ONIE_TLVINFO_TYPE_CODE_LABEL_REVISION, ONIE_TLVINFO_TYPE_CODE_PLATFORM_NAME, ONIE_TLVINFO_TYPE_CODE_ONIE_VERSION, ONIE_TLVINFO_TYPE_CODE_NUM_MACS, ONIE_TLVINFO_TYPE_CODE_MANUFACTURER, ONIE_TLVINFO_TYPE_CODE_COUNTRY_CODE, ONIE_TLVINFO_TYPE_CODE_VENDOR, ONIE_TLVINFO_TYPE_CODE_DIAG_VERSION, ONIE_TLVINFO_TYPE_CODE_SERVICE_TAG, ONIE_TLVINFO_TYPE_CODE_VENDOR_EXT, ONIE_TLVINFO_TYPE_CODE_CRC32 ] MINIMUM_REQUIRED_TYPE_CODES_LIST = [ ONIE_TLVINFO_TYPE_CODE_SERIAL_NUMBER, ONIE_TLVINFO_TYPE_CODE_BASE_MAC_ADDR, ONIE_TLVINFO_TYPE_CODE_CRC32 ] syseeprom_info_dict = chassis.get_system_eeprom_info(platform_api_conn) pytest_assert(syseeprom_info_dict is not None, "Failed to retrieve system EEPROM data") pytest_assert(isinstance(syseeprom_info_dict, dict), "System EEPROM data is not in the expected format") syseeprom_type_codes_list = syseeprom_info_dict.keys() # Ensure that all keys in the resulting dictionary are valid ONIE TlvInfo type codes pytest_assert(set(syseeprom_type_codes_list) <= set(VALID_ONIE_TLVINFO_TYPE_CODES_LIST), "Invalid TlvInfo type code found") # Ensure that we were able to obtain the minimum required type codes pytest_assert(set(MINIMUM_REQUIRED_TYPE_CODES_LIST) <= set(syseeprom_type_codes_list), "Minimum required TlvInfo type codes not provided") # Ensure the base MAC address is sane base_mac = syseeprom_info_dict[ONIE_TLVINFO_TYPE_CODE_BASE_MAC_ADDR] pytest_assert(base_mac is not None, "Failed to retrieve base MAC address") pytest_assert(re.match(REGEX_MAC_ADDRESS, base_mac), "Base MAC address appears to be incorrect") # Ensure the serial number is sane serial = syseeprom_info_dict[ONIE_TLVINFO_TYPE_CODE_SERIAL_NUMBER] pytest_assert(serial is not None, "Failed to retrieve serial number") pytest_assert(re.match(REGEX_SERIAL_NUMBER, serial), "Serial number appears to be incorrect") if 'syseeprom_info' in duthost.host.options['inventory_manager'].get_host(duthost.hostname).vars: expected_syseeprom_info_dict = duthost.host.options['inventory_manager'].get_host(duthost.hostname).vars['syseeprom_info'] pytest_assert(syseeprom_info_dict == expected_syseeprom_info_dict, "System EEPROM info is incorrect") else: logger.warning('Inventory file does not contain system EEPROM info for {}'.format(duthost.hostname)) def test_get_reboot_cause(self, duthost, localhost, platform_api_conn): # TODO: Compare return values to potential combinations reboot_cause = chassis.get_reboot_cause(platform_api_conn) # Actual return value is a tuple, but since we're using the HTTP server # to make the call and it uses JSON, the tuple is changed to a list pytest_assert(reboot_cause is not None, "Failed to retrieve reboot cause") pytest_assert(isinstance(reboot_cause, list) and len(reboot_cause) == 2, "Reboot cause appears to be incorrect") def
(self, duthost, localhost, platform_api_conn): # TODO: Ensure the number of components and that the returned list is correct for this platform try: num_components = int(chassis.get_num_components(platform_api_conn)) except: pytest.fail("num_components is not an integer") component_list = chassis.get_all_components(platform_api_conn) pytest_assert(component_list is not None, "Failed to retrieve components") pytest_assert(isinstance(component_list, list) and len(component_list) == num_components, "Components appear to be incorrect") for i in range(num_components): component = chassis.get_component(platform_api_conn, i) self.expect(component and component == component_list[i], "Component {} is incorrect".format(i)) self.assert_expectations() def test_modules(self, duthost, localhost, platform_api_conn): # TODO: Ensure the number of modules and that the returned list is correct for this platform try: num_modules = int(chassis.get_num_modules(platform_api_conn)) except: pytest.fail("num_modules is not an integer") module_list = chassis.get_all_modules(platform_api_conn) pytest_assert(module_list is not None, "Failed to retrieve modules") pytest_assert(isinstance(module_list, list) and len(module_list) == num_modules, "Modules appear to be incorrect") for i in range(num_modules): module = chassis.get_module(platform_api_conn, i) self.expect(module and module == module_list[i], "Module {} is incorrect".format(i)) self.assert_expectations() def test_fans(self, duthost, localhost, platform_api_conn): # TODO: Ensure the number of fans and that the returned list is correct for this platform try: num_fans = int(chassis.get_num_fans(platform_api_conn)) except: pytest.fail("num_fans is not an integer") fan_list = chassis.get_all_fans(platform_api_conn) pytest_assert(fan_list is not None, "Failed to retrieve fans") pytest_assert(isinstance(fan_list, list) and len(fan_list) == num_fans, "Fans appear to be incorrect") for i in range(num_fans): fan = chassis.get_fan(platform_api_conn, i) self.expect(fan and fan == fan_list[i], "Fan {} is incorrect".format(i)) self.assert_expectations() def test_fan_drawers(self, duthost, localhost, platform_api_conn): # TODO: Ensure the number of fan drawers and that the returned list is correct for this platform try: num_fan_drawers = int(chassis.get_num_fan_drawers(platform_api_conn)) except: pytest.fail("num_fan_drawers is not an integer") fan_drawer_list = chassis.get_all_fan_drawers(platform_api_conn) pytest_assert(fan_drawer_list is not None, "Failed to retrieve fan drawers") pytest_assert(isinstance(fan_drawer_list, list) and len(fan_drawer_list) == num_fan_drawers, "Fan drawerss appear to be incorrect") for i in range(num_fan_drawers): fan_drawer = chassis.get_fan_drawer(platform_api_conn, i) self.expect(fan_drawer and fan_drawer == fan_drawer_list[i], "Fan drawer {} is incorrect".format(i)) self.assert_expectations() def test_psus(self, duthost, localhost, platform_api_conn): # TODO: Ensure the number of PSUs and that the returned list is correct for this platform try: num_psus = int(chassis.get_num_psus(platform_api_conn)) except: pytest.fail("num_psus is not an integer") psu_list = chassis.get_all_psus(platform_api_conn) pytest_assert(psu_list is not None, "Failed to retrieve PSUs") pytest_assert(isinstance(psu_list, list) and len(psu_list) == num_psus, "PSUs appear to be incorrect") for i in range(num_psus): psu = chassis.get_psu(platform_api_conn, i) self.expect(psu and psu == psu_list[i], "PSU {} is incorrect".format(i)) self.assert_expectations() def test_thermals(self, duthost, localhost, platform_api_conn): # TODO: Ensure the number of thermals and that the returned list is correct for this platform try: num_thermals = int(chassis.get_num_thermals(platform_api_conn)) except: pytest.fail("num_thermals is not an integer") thermal_list = chassis.get_all_thermals(platform_api_conn) pytest_assert(thermal_list is not None, "Failed to retrieve thermals") pytest_assert(isinstance(thermal_list, list) and len(thermal_list) == num_thermals, "Thermals appear to be incorrect") for i in range(num_thermals): thermal = chassis.get_thermal(platform_api_conn, i) self.expect(thermal and thermal == thermal_list[i], "Thermal {} is incorrect".format(i)) self.assert_expectations() def test_sfps(self, duthost, localhost, platform_api_conn): # TODO: Ensure the number of SFPs and that the returned list is correct for this platform try: num_sfps = int(chassis.get_num_sfps(platform_api_conn)) except: pytest.fail("num_sfps is not an integer") sfp_list = chassis.get_all_sfps(platform_api_conn) pytest_assert(sfp_list is not None, "Failed to retrieve SFPs") pytest_assert(isinstance(sfp_list, list) and len(sfp_list) == num_sfps, "SFPs appear to be incorrect") for i in range(num_sfps): sfp = chassis.get_sfp(platform_api_conn, i) self.expect(sfp and sfp == sfp_list[i], "SFP {} is incorrect".format(i)) self.assert_expectations() def test_status_led(self, duthost, localhost, platform_api_conn): # TODO: Get a platform-specific list of available colors for the status LED LED_COLOR_LIST = [ "off", "red", "amber", "green", ] for color in LED_COLOR_LIST: result = chassis.set_status_led(platform_api_conn, color) if self.expect(result is not None, "Failed to perform set_status_led"): self.expect(result is True, "Failed to set status_led to {}".format(color)) color_actual = chassis.get_status_led(platform_api_conn) if self.expect(color_actual is not None, "Failed to retrieve status_led"): if self.expect(isinstance(color_actual, str), "Status LED color appears incorrect"): self.expect(color == color_actual, "Status LED color incorrect (expected: {}, actual: {})".format(color, color_actual)) self.assert_expectations() def test_get_thermal_manager(self, duthost, localhost, platform_api_conn): thermal_mgr = chassis.get_thermal_manager(platform_api_conn) pytest_assert(thermal_mgr is not None, "Failed to retrieve thermal manager") def test_get_watchdog(self, duthost, localhost, platform_api_conn): watchdog = chassis.get_watchdog(platform_api_conn) pytest_assert(watchdog is not None, "Failed to retrieve watchdog") def test_get_eeprom(self, duthost, localhost, platform_api_conn): eeprom = chassis.get_eeprom(platform_api_conn) pytest_assert(eeprom is not None, "Failed to retrieve system EEPROM")
test_components
custom.rs
//! For supporting additional types with the Pg backend (or other //! future backends). //! //! For an example of usage, see `butane/tests/custom_pg.rs` in the //! source repository. Not supported for the Sqlite backend as Sqlite //! supports a very limited set of types to begin with. use serde::{Deserialize, Serialize}; use std::fmt; /// For use with [SqlType::Custom](crate::SqlType) #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum SqlTypeCustom { #[cfg(feature = "pg")] Pg(#[serde(with = "pgtypeser")] postgres::types::Type), } /// For use with [SqlVal::Custom](crate::SqlVal) #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SqlValCustom { #[cfg(feature = "pg")] Pg { #[serde(with = "pgtypeser")] ty: postgres::types::Type, data: Vec<u8>, }, } impl SqlValCustom { pub fn as_valref(&self) -> SqlValRefCustom { match self { #[cfg(feature = "pg")] SqlValCustom::Pg { ty, data } => SqlValRefCustom::PgBytes { ty: ty.clone(), data: data.as_ref(), }, #[cfg(not(feature = "pg"))] _ => panic!("SqlValCustom unsupported"), } } } impl fmt::Display for SqlValCustom { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { #[cfg(feature = "pg")] SqlValCustom::Pg { ty, .. } => { f.write_str(&format!("<custom PG value of type {}>", ty)) } #[cfg(not(feature = "pg"))] _ => f.write_str(&format!("<unknown custom value>")), } } } #[cfg(feature = "pg")] impl postgres::types::ToSql for SqlValCustom { fn to_sql( &self, wanted_ty: &postgres::types::Type, out: &mut bytes::BytesMut, ) -> std::result::Result< postgres::types::IsNull, Box<dyn std::error::Error + 'static + Sync + Send>, > { use bytes::BufMut; match self { SqlValCustom::Pg { ty, data } => { if ty != wanted_ty { return Err(Box::new(crate::Error::Internal(format!( "postgres type mismatch. Wanted {} but have {}", wanted_ty, ty )))); } out.put(data.as_ref()) } } Ok(postgres::types::IsNull::No) } fn accepts(_: &postgres::types::Type) -> bool { // Unfortunately, this is a type method rather than an instance method, // so we don't know what this specific instance accepts :( true } postgres::types::to_sql_checked!(); } /// For use with [SqlValRef::Custom](crate::SqlValRef) #[derive(Clone, Debug)] pub enum SqlValRefCustom<'a> { /// Used with Postgres, but suitable only for input (e.g. input to /// a query), not suitable for parsing in a [FromSql](crate::FromSql) implementation. #[cfg(feature = "pg")] PgToSql { ty: postgres::types::Type, tosql: &'a (dyn postgres::types::ToSql + Sync), }, /// The Pg backend will return SqlValRef instances of this /// type. May also be used by [ToSql](crate::ToSql) /// implementations, but may be less convenient than `PgToSql` for that purpose. #[cfg(feature = "pg")] PgBytes { ty: postgres::types::Type, data: &'a [u8], }, #[cfg(not(feature = "pg"))] Phantom(std::marker::PhantomData<&'a ()>), } impl From<SqlValRefCustom<'_>> for SqlValCustom { fn from(r: SqlValRefCustom) -> SqlValCustom { match r { #[cfg(feature = "pg")] SqlValRefCustom::PgToSql { ty, tosql } => { let mut b = bytes::BytesMut::new(); // TODO avoid unwrap tosql.to_sql_checked(&ty, &mut b).unwrap(); SqlValCustom::Pg { ty, data: b.to_vec(), } } #[cfg(feature = "pg")] SqlValRefCustom::PgBytes { ty, data } => SqlValCustom::Pg { ty, data: data.into(), }, #[cfg(not(feature = "pg"))] SqlValRefCustom::Phantom(_) => { panic!("phantom SqlValRefCustom should not be instantiated") } } } } #[cfg(feature = "pg")] mod pgtypeser { use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub fn serialize<S>(ty: &postgres::types::Type, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let ty = SerializablePgType::from(ty.clone()); ty.serialize(serializer) } pub fn deserialize<'de, D>(deserializer: D) -> Result<postgres::types::Type, D::Error> where D: Deserializer<'de>, { Ok(SerializablePgType::deserialize(deserializer)?.into()) } //Serializable version of postgres::types::Type #[derive(Serialize, Deserialize, Clone)] struct SerializablePgType { name: String, oid: u32, kind: Box<SerializablePgKind>, schema: String, } impl From<postgres::types::Type> for SerializablePgType { fn from(ty: postgres::types::Type) -> Self { Self { name: ty.name().to_string(), oid: ty.oid(), kind: Box::new(ty.kind().clone().into()), schema: ty.schema().to_string(), } } } impl From<SerializablePgType> for postgres::types::Type { fn from(spt: SerializablePgType) -> postgres::types::Type { postgres::types::Type::new(spt.name, spt.oid, (*spt.kind).into(), spt.schema) } } #[derive(Serialize, Deserialize, Clone)] enum SerializablePgKind { Simple, Enum(Vec<String>), Pseudo, Array(SerializablePgType), Range(SerializablePgType), Domain(SerializablePgType), Composite(Vec<SerializablePgField>), } impl From<postgres::types::Kind> for SerializablePgKind { fn from(k: postgres::types::Kind) -> Self { use postgres::types::Kind::*; match k { Simple => Self::Simple, Enum(v) => Self::Enum(v), Pseudo => Self::Pseudo, Array(ty) => Self::Array(ty.into()), Range(ty) => Self::Range(ty.into()), Domain(ty) => Self::Domain(ty.into()), Composite(v) => Self::Composite(v.into_iter().map(|f| f.into()).collect()), // TODO why is rustc requiring wildcard here _ => panic!("Unhandled variant"), } } } impl From<SerializablePgKind> for postgres::types::Kind { fn from(spk: SerializablePgKind) -> postgres::types::Kind { use postgres::types::Kind::*; match spk { SerializablePgKind::Simple => Simple, SerializablePgKind::Enum(v) => Enum(v), SerializablePgKind::Pseudo => Pseudo, SerializablePgKind::Array(ty) => Array(ty.into()), SerializablePgKind::Range(ty) => Range(ty.into()), SerializablePgKind::Domain(ty) => Domain(ty.into()), SerializablePgKind::Composite(v) => {
} } } #[derive(Serialize, Deserialize, Clone)] struct SerializablePgField { name: String, ty: SerializablePgType, } impl From<postgres::types::Field> for SerializablePgField { fn from(f: postgres::types::Field) -> Self { Self { name: f.name().to_string(), ty: f.type_().clone().into(), } } } impl From<SerializablePgField> for postgres::types::Field { fn from(spf: SerializablePgField) -> postgres::types::Field { postgres::types::Field::new(spf.name, spf.ty.into()) } } }
Composite(v.into_iter().map(|f| f.into()).collect()) }
gview.go
package main import ( "fmt" "github.com/gogf/gf/g" ) func main()
{ v := g.View() b, err := v.Parse("gview.tpl", map[string]interface{} { "k" : "v", }) if err != nil { panic(err) } fmt.Println(string(b)) }
item-monitoring-list.js
import request from '../../utils/request' import APIUrl from '../apiUrl/basic-information-management' // 新增保存 export function saveItemMonitoring(params) { return request({ url: APIUrl.itemMonitoringList.saveItemMonitoring, method: 'post', data: params }) } // 修改保存 export function updateItemMonitoring(params) { return request({ url: APIUrl.itemMonitoringList.updateItemMonitoring, method: 'post', data: params }) } // 删除 export function deleteItemMonitoring(params) { return request({ url: APIUrl.itemMonitoringList.deleteItemMonitoring, method: 'post', data: params }) } // 新增页面,选择服务项目 export function listServiceItem(params) { return request({ url: APIUrl.itemMonitoringList.listServiceItem, method: 'post', data: params }) } // 上报 export function reportItemMonitoring(params) { return request({ url: APIUrl.itemMonitoringList.reportItemMonitoring, method: 'post', data: params }) } // 查询 export function listItemMonitoring(params) { return request({ url: APIUrl.itemMonitoringList.listItemMonitoring, method: 'post',
// 根据医疗机构编码查询开展科室 export function listDeptByMedinsId(params) { return request({ url: APIUrl.itemMonitoringList.listDeptByMedinsId, method: 'post', data: params }) } // 根据省份编码查询统筹区信息 export function listPoolAreaByProv(params) { return request({ url: APIUrl.newItemFilling.listPoolAreaByProv, method: 'post', data: params }) } // 详情 export function getItemMonitoringDetail(params) { return request({ url: APIUrl.itemMonitoringList.getItemMonitoringDetail, method: 'post', data: params }) } export default{ saveItemMonitoring, updateItemMonitoring, deleteItemMonitoring, listServiceItem, reportItemMonitoring, listItemMonitoring, listDeptByMedinsId, listPoolAreaByProv, getItemMonitoringDetail }
data: params }) }
subscribe_seqstart.rs
#[doc = "Register `SUBSCRIBE_SEQSTART[%s]` reader"] pub struct R(crate::R<SUBSCRIBE_SEQSTART_SPEC>); impl core::ops::Deref for R { type Target = crate::R<SUBSCRIBE_SEQSTART_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<SUBSCRIBE_SEQSTART_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<SUBSCRIBE_SEQSTART_SPEC>) -> Self { R(reader) } } #[doc = "Register `SUBSCRIBE_SEQSTART[%s]` writer"] pub struct W(crate::W<SUBSCRIBE_SEQSTART_SPEC>); impl core::ops::Deref for W { type Target = crate::W<SUBSCRIBE_SEQSTART_SPEC>; #[inline(always)] fn
(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<SUBSCRIBE_SEQSTART_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<SUBSCRIBE_SEQSTART_SPEC>) -> Self { W(writer) } } #[doc = "Field `CHIDX` reader - DPPI channel that task SEQSTART\\[n\\] will subscribe to"] pub struct CHIDX_R(crate::FieldReader<u8, u8>); impl CHIDX_R { pub(crate) fn new(bits: u8) -> Self { CHIDX_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for CHIDX_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CHIDX` writer - DPPI channel that task SEQSTART\\[n\\] will subscribe to"] pub struct CHIDX_W<'a> { w: &'a mut W, } impl<'a> CHIDX_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff); self.w } } #[doc = "\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EN_A { #[doc = "0: Disable subscription"] DISABLED = 0, #[doc = "1: Enable subscription"] ENABLED = 1, } impl From<EN_A> for bool { #[inline(always)] fn from(variant: EN_A) -> Self { variant as u8 != 0 } } #[doc = "Field `EN` reader - "] pub struct EN_R(crate::FieldReader<bool, EN_A>); impl EN_R { pub(crate) fn new(bits: bool) -> Self { EN_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EN_A { match self.bits { false => EN_A::DISABLED, true => EN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { **self == EN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { **self == EN_A::ENABLED } } impl core::ops::Deref for EN_R { type Target = crate::FieldReader<bool, EN_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `EN` writer - "] pub struct EN_W<'a> { w: &'a mut W, } impl<'a> EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EN_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Disable subscription"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(EN_A::DISABLED) } #[doc = "Enable subscription"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(EN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | ((value as u32 & 0x01) << 31); self.w } } impl R { #[doc = "Bits 0:7 - DPPI channel that task SEQSTART\\[n\\] will subscribe to"] #[inline(always)] pub fn chidx(&self) -> CHIDX_R { CHIDX_R::new((self.bits & 0xff) as u8) } #[doc = "Bit 31"] #[inline(always)] pub fn en(&self) -> EN_R { EN_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:7 - DPPI channel that task SEQSTART\\[n\\] will subscribe to"] #[inline(always)] pub fn chidx(&mut self) -> CHIDX_W { CHIDX_W { w: self } } #[doc = "Bit 31"] #[inline(always)] pub fn en(&mut self) -> EN_W { EN_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "Description collection: Subscribe configuration for task SEQSTART\\[n\\]\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [subscribe_seqstart](index.html) module"] pub struct SUBSCRIBE_SEQSTART_SPEC; impl crate::RegisterSpec for SUBSCRIBE_SEQSTART_SPEC { type Ux = u32; } #[doc = "`read()` method returns [subscribe_seqstart::R](R) reader structure"] impl crate::Readable for SUBSCRIBE_SEQSTART_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [subscribe_seqstart::W](W) writer structure"] impl crate::Writable for SUBSCRIBE_SEQSTART_SPEC { type Writer = W; } #[doc = "`reset()` method sets SUBSCRIBE_SEQSTART[%s] to value 0"] impl crate::Resettable for SUBSCRIBE_SEQSTART_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
deref
msggetblocks.go
// Copyright (c) 2013-2016 The btcsuite developers // Copyright (c) 2015-2016 The Decred developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package wire import ( "fmt" "io" "github.com/decred/dcrd/chaincfg/chainhash" ) // MaxBlockLocatorsPerMsg is the maximum number of block locator hashes allowed // per message. const MaxBlockLocatorsPerMsg = 500 // MsgGetBlocks implements the Message interface and represents a decred // getblocks message. It is used to request a list of blocks starting after the // last known hash in the slice of block locator hashes. The list is returned // via an inv message (MsgInv) and is limited by a specific hash to stop at or // the maximum number of blocks per message, which is currently 500. // // Set the HashStop field to the hash at which to stop and use // AddBlockLocatorHash to build up the list of block locator hashes. // // The algorithm for building the block locator hashes should be to add the // hashes in reverse order until you reach the genesis block. In order to keep // the list of locator hashes to a reasonable number of entries, first add the // most recent 10 block hashes, then double the step each loop iteration to // exponentially decrease the number of hashes the further away from head and // closer to the genesis block you get. type MsgGetBlocks struct { ProtocolVersion uint32 BlockLocatorHashes []*chainhash.Hash HashStop chainhash.Hash } // AddBlockLocatorHash adds a new block locator hash to the message. func (msg *MsgGetBlocks) AddBlockLocatorHash(hash *chainhash.Hash) error { if len(msg.BlockLocatorHashes)+1 > MaxBlockLocatorsPerMsg { str := fmt.Sprintf("too many block locator hashes for message [max %v]", MaxBlockLocatorsPerMsg) return messageError("MsgGetBlocks.AddBlockLocatorHash", str) } msg.BlockLocatorHashes = append(msg.BlockLocatorHashes, hash) return nil } // BtcDecode decodes r using the Decred protocol encoding into the receiver. // This is part of the Message interface implementation. func (msg *MsgGetBlocks) BtcDecode(r io.Reader, pver uint32) error { err := readElement(r, &msg.ProtocolVersion) if err != nil { return err } // Read num block locator hashes and limit to max. count, err := ReadVarInt(r, pver) if err != nil { return err } if count > MaxBlockLocatorsPerMsg { str := fmt.Sprintf("too many block locator hashes for message "+ "[count %v, max %v]", count, MaxBlockLocatorsPerMsg) return messageError("MsgGetBlocks.BtcDecode", str) } // Create a contiguous slice of hashes to deserialize into in order to // reduce the number of allocations. locatorHashes := make([]chainhash.Hash, count) msg.BlockLocatorHashes = make([]*chainhash.Hash, 0, count) for i := uint64(0); i < count; i++ { hash := &locatorHashes[i] err := readElement(r, hash) if err != nil { return err } msg.AddBlockLocatorHash(hash) } return readElement(r, &msg.HashStop) } // BtcEncode encodes the receiver to w using the Decred protocol encoding. // This is part of the Message interface implementation. func (msg *MsgGetBlocks) BtcEncode(w io.Writer, pver uint32) error { count := len(msg.BlockLocatorHashes) if count > MaxBlockLocatorsPerMsg { str := fmt.Sprintf("too many block locator hashes for message "+ "[count %v, max %v]", count, MaxBlockLocatorsPerMsg) return messageError("MsgGetBlocks.BtcEncode", str) } err := writeElement(w, msg.ProtocolVersion) if err != nil { return err } err = WriteVarInt(w, pver, uint64(count)) if err != nil { return err } for _, hash := range msg.BlockLocatorHashes { err = writeElement(w, hash) if err != nil { return err } } return writeElement(w, &msg.HashStop) } // Command returns the protocol command string for the message. This is part // of the Message interface implementation. func (msg *MsgGetBlocks) Command() string { return CmdGetBlocks } // MaxPayloadLength returns the maximum length the payload can be for the // receiver. This is part of the Message interface implementation. func (msg *MsgGetBlocks) MaxPayloadLength(pver uint32) uint32 { // Protocol version 4 bytes + num hashes (varInt) + max block locator // hashes + hash stop. return 4 + MaxVarIntPayload + (MaxBlockLocatorsPerMsg * chainhash.HashSize) + chainhash.HashSize } // NewMsgGetBlocks returns a new Decred getblocks message that conforms to the // Message interface using the passed parameters and defaults for the remaining // fields. func
(hashStop *chainhash.Hash) *MsgGetBlocks { return &MsgGetBlocks{ ProtocolVersion: ProtocolVersion, BlockLocatorHashes: make([]*chainhash.Hash, 0, MaxBlockLocatorsPerMsg), HashStop: *hashStop, } }
NewMsgGetBlocks
lib.rs
use std::thread; use std::sync::mpsc; use std::sync::Arc; use std::sync::Mutex; pub struct ThreadPool { workers: Vec<Worker>, sender: mpsc::Sender<Message>, } type Job = Box<dyn FnOnce() + Send + 'static>; enum Message { NewJob(Job), Terminate, } impl ThreadPool { /// Create a new ThreadPool. /// /// The size is the number of threads in the pool. /// /// # Panics /// /// The `new` function will panic if the size is zero pub fn
(size: usize) -> ThreadPool { assert!(size > 0); let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let mut workers = Vec::with_capacity(size); for id in 0..size { workers.push(Worker::new(id, Arc::clone(&receiver))); } ThreadPool { workers, sender } } pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static, { let job = Box::new(f); self.sender.send(Message::NewJob(job)).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { println!("Sending terminate message to all workers."); for _ in &self.workers { self.sender.send(Message::Terminate).unwrap(); } println!("Shutting down all workers."); for worker in &mut self.workers { println!("Shutting down worker {}", worker.id); if let Some(thread) = worker.thread.take() { thread.join().unwrap(); } } } } struct Worker { id: usize, thread: Option<thread::JoinHandle<()>>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker { let thread = thread::spawn(move || loop { let message = receiver.lock().unwrap().recv().unwrap(); match message { Message::NewJob(job) => { println!("Worker {} got a job; executing.", id); job(); } Message::Terminate => { println!("Worker {} was told to terminate.", id); break; } } }); Worker { id, thread: Some(thread), } } }
new
nullseed.go
package desync import ( "context" "fmt" "io" "io/ioutil" "os" "path/filepath" ) type nullChunkSeed struct { id ChunkID blockfile *os.File canReflink bool } func
(dstFile string, blocksize uint64, max uint64) (*nullChunkSeed, error) { blockfile, err := ioutil.TempFile(filepath.Dir(dstFile), ".tmp-block") if err != nil { return nil, err } var canReflink bool if CanClone(dstFile, blockfile.Name()) { canReflink = true b := make([]byte, blocksize) if _, err := blockfile.Write(b); err != nil { return nil, err } } return &nullChunkSeed{ id: NewNullChunk(max).ID, canReflink: canReflink, blockfile: blockfile, }, nil } func (s *nullChunkSeed) close() error { if s.blockfile != nil { s.blockfile.Close() return os.Remove(s.blockfile.Name()) } return nil } func (s *nullChunkSeed) LongestMatchWith(chunks []IndexChunk) (int, SeedSegment) { if len(chunks) == 0 { return 0, nil } var n int for _, c := range chunks { if c.ID != s.id { break } n++ } if n == 0 { return 0, nil } return n, &nullChunkSection{ from: chunks[0].Start, to: chunks[n-1].Start + chunks[n-1].Size, blockfile: s.blockfile, canReflink: s.canReflink, } } func (s *nullChunkSeed) RegenerateIndex(ctx context.Context, n int, attempt int, seedNumber int) error { panic("A nullseed can't be regenerated") } func (s *nullChunkSeed) SetInvalid(value bool) { panic("A nullseed is never expected to be invalid") } func (s *nullChunkSeed) IsInvalid() bool { // A nullseed is never expected to be invalid return false } type nullChunkSection struct { from, to uint64 blockfile *os.File canReflink bool } func (s *nullChunkSection) Validate(file *os.File) error { // We always assume a nullseed to be valid return nil } func (s *nullChunkSection) FileName() string { return "" } func (s *nullChunkSection) Size() uint64 { return s.to - s.from } func (s *nullChunkSection) WriteInto(dst *os.File, offset, length, blocksize uint64, isBlank bool) (uint64, uint64, error) { if length != s.Size() { return 0, 0, fmt.Errorf("unable to copy %d bytes to %s : wrong size", length, dst.Name()) } // When cloning isn'a available we'd normally have to copy the 0 bytes into // the target range. But if that's already blank (because it's a new/truncated // file) there's no need to copy 0 bytes. if !s.canReflink { if isBlank { return 0, 0, nil } return s.copy(dst, offset, s.Size()) } return s.clone(dst, offset, length, blocksize) } func (s *nullChunkSection) copy(dst *os.File, offset, length uint64) (uint64, uint64, error) { if _, err := dst.Seek(int64(offset), os.SEEK_SET); err != nil { return 0, 0, err } // Copy using a fixed buffer. Using io.Copy() with a LimitReader will make it // create a buffer matching N of the LimitReader which can be too large copied, err := io.CopyBuffer(dst, io.LimitReader(nullReader{}, int64(length)), make([]byte, 64*1024)) return uint64(copied), 0, err } func (s *nullChunkSection) clone(dst *os.File, offset, length, blocksize uint64) (uint64, uint64, error) { dstAlignStart := (offset/blocksize + 1) * blocksize dstAlignEnd := (offset + length) / blocksize * blocksize // fill the area before the first aligned block var copied, cloned uint64 c1, _, err := s.copy(dst, offset, dstAlignStart-offset) if err != nil { return c1, 0, err } copied += c1 // fill the area after the last aligned block c2, _, err := s.copy(dst, dstAlignEnd, offset+length-dstAlignEnd) if err != nil { return copied + c2, 0, err } copied += c2 for blkOffset := dstAlignStart; blkOffset < dstAlignEnd; blkOffset += blocksize { if err := CloneRange(dst, s.blockfile, 0, blocksize, blkOffset); err != nil { return copied, cloned, err } cloned += blocksize } return copied, cloned, nil } type nullReader struct{} func (r nullReader) Read(b []byte) (n int, err error) { for i := range b { b[i] = 0 } return len(b), nil }
newNullChunkSeed
type_converter.rs
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::{ conversion::codegen_cpp::AdditionalNeed, conversion::{ api::{TypeApiDetails, UnanalyzedApi}, codegen_cpp::type_to_cpp::type_to_cpp, ConvertError, }, known_types::KNOWN_TYPES, types::{make_ident, Namespace, TypeName}, }; use std::collections::{HashMap, HashSet}; use syn::{ parse_quote, punctuated::Punctuated, GenericArgument, PathArguments, PathSegment, Type, TypePath, TypePtr, }; /// Results of some type conversion, annotated with a list of every type encountered, /// and optionally any extra APIs we need in order to use this type. pub(crate) struct Annotated<T> { pub(crate) ty: T, pub(crate) types_encountered: HashSet<TypeName>, pub(crate) extra_apis: Vec<UnanalyzedApi>, pub(crate) requires_unsafe: bool, } impl<T> Annotated<T> { fn new( ty: T, types_encountered: HashSet<TypeName>, extra_apis: Vec<UnanalyzedApi>, requires_unsafe: bool, ) -> Self { Self { ty, types_encountered, extra_apis, requires_unsafe, } } fn map<T2, F: FnOnce(T) -> T2>(self, fun: F) -> Annotated<T2> { Annotated { ty: fun(self.ty), types_encountered: self.types_encountered, extra_apis: self.extra_apis, requires_unsafe: self.requires_unsafe, } } } /// A type which can convert from a type encountered in `bindgen` /// output to the sort of type we should represeent to `cxx`. /// As a simple example, `std::string` should be replaced /// with [CxxString]. This also involves keeping track /// of typedefs, and any instantiated concrete types. /// /// This object is a bit of a pest. The information here /// is compiled during the parsing phase (which is why it lives /// in the parse mod) but is used during various other phases. /// As such it contributes to both the parsing and analysis phases. /// It's possible that the information here largely duplicates /// information stored elsewhere in the list of `Api`s, or can /// easily be moved into it, which would enable us to /// distribute this logic elsewhere. pub(crate) struct TypeConverter { types_found: Vec<TypeName>, typedefs: HashMap<TypeName, Type>, concrete_templates: HashMap<String, TypeName>, } impl TypeConverter { pub(crate) fn new() -> Self { Self { types_found: Vec::new(), typedefs: HashMap::new(), concrete_templates: HashMap::new(), } } pub(crate) fn push(&mut self, ty: TypeName) { self.types_found.push(ty); } pub(crate) fn insert_typedef(&mut self, id: TypeName, target: Type) { self.typedefs.insert(id, target); } pub(crate) fn convert_boxed_type( &mut self, ty: Box<Type>, ns: &Namespace, convert_ptrs_to_reference: bool, ) -> Result<Annotated<Box<Type>>, ConvertError> { Ok(self .convert_type(*ty, ns, convert_ptrs_to_reference)? .map(Box::new)) } pub(crate) fn convert_type( &mut self, ty: Type, ns: &Namespace, convert_ptrs_to_reference: bool, ) -> Result<Annotated<Type>, ConvertError> { let result = match ty { Type::Path(p) => { let newp = self.convert_type_path(p, ns)?; if let Type::Path(newpp) = &newp.ty { // Special handling because rust_Str (as emitted by bindgen) // doesn't simply get renamed to a different type _identifier_. // This plain type-by-value (as far as bindgen is concerned) // is actually a &str. if KNOWN_TYPES.should_dereference_in_cpp(newpp) { Annotated::new( Type::Reference(parse_quote! { &str }), newp.types_encountered, newp.extra_apis, false, ) } else { newp } } else { newp } } Type::Reference(mut r) => { let innerty = self.convert_boxed_type(r.elem, ns, false)?; r.elem = innerty.ty; Annotated::new( Type::Reference(r), innerty.types_encountered, innerty.extra_apis, false, ) } Type::Ptr(ptr) if convert_ptrs_to_reference => { self.convert_ptr_to_reference(ptr, ns)? } Type::Ptr(mut ptr) => { crate::known_types::ensure_pointee_is_valid(&ptr)?; let innerty = self.convert_boxed_type(ptr.elem, ns, false)?; ptr.elem = innerty.ty; Annotated::new( Type::Ptr(ptr), innerty.types_encountered, innerty.extra_apis, true, ) } _ => Annotated::new(ty, HashSet::new(), Vec::new(), false), }; Ok(result) } fn convert_type_path( &mut self, mut typ: TypePath, ns: &Namespace, ) -> Result<Annotated<Type>, ConvertError> { // First, qualify any unqualified paths. if typ.path.segments.iter().next().unwrap().ident != "root" { let ty = TypeName::from_type_path(&typ); // If the type looks like it is unqualified, check we know it // already, and if not, qualify it according to the current // namespace. This is a bit of a shortcut compared to having a full // resolution pass which can search all known namespaces. if !KNOWN_TYPES.is_known_type(&ty) { let num_segments = typ.path.segments.len(); if num_segments > 1 { return Err(ConvertError::UnsupportedBuiltInType(ty)); } if !self.types_found.contains(&ty) { typ.path.segments = std::iter::once(&"root".to_string()) .chain(ns.iter()) .map(|s| { let i = make_ident(s); parse_quote! { #i } }) .chain(typ.path.segments.into_iter()) .collect(); } } } let original_tn = TypeName::from_type_path(&typ); let mut deps = HashSet::new(); // Now convert this type itself. deps.insert(original_tn.clone()); // First let's see if this is a typedef. let (typ, tn) = match self.resolve_typedef(&original_tn) { None => (typ, original_tn), Some(Type::Path(resolved_tp)) => { let resolved_tn = TypeName::from_type_path(&resolved_tp); deps.insert(resolved_tn.clone()); (resolved_tp.clone(), resolved_tn) } Some(other) => { return Ok(Annotated::new( other.clone(), HashSet::new(), Vec::new(), false, )) } }; // Now let's see if it's a known type. let mut typ = match KNOWN_TYPES.known_type_substitute_path(&typ) { Some(mut substitute_type) => { if let Some(last_seg_args) = typ.path.segments.into_iter().last().map(|ps| ps.arguments) { let last_seg = substitute_type.path.segments.last_mut().unwrap(); last_seg.arguments = last_seg_args; } substitute_type } None => typ, }; let mut extra_apis = Vec::new(); // Finally let's see if it's generic. if let Some(last_seg) = Self::get_generic_args(&mut typ) { if KNOWN_TYPES.is_cxx_acceptable_generic(&tn) { // this is a type of generic understood by cxx (e.g. CxxVector) // so let's convert any generic type arguments. This recurses. crate::known_types::confirm_inner_type_is_acceptable_generic_payload( &last_seg.arguments, &tn, )?; if let PathArguments::AngleBracketed(ref mut ab) = last_seg.arguments { let mut innerty = self.convert_punctuated(ab.args.clone(), ns)?; ab.args = innerty.ty; deps.extend(innerty.types_encountered.drain()); } } else { // Oh poop. It's a generic type which cxx won't be able to handle. // We'll have to come up with a concrete type in both the cxx::bridge (in Rust) // and a corresponding typedef in C++. let (new_tn, api) = self.get_templated_typename(&Type::Path(typ))?; extra_apis.extend(api.into_iter()); deps.remove(&tn); typ = new_tn.to_type_path(); deps.insert(new_tn); } } Ok(Annotated::new(Type::Path(typ), deps, extra_apis, false)) } fn get_generic_args(typ: &mut TypePath) -> Option<&mut PathSegment>
fn convert_punctuated<P>( &mut self, pun: Punctuated<GenericArgument, P>, ns: &Namespace, ) -> Result<Annotated<Punctuated<GenericArgument, P>>, ConvertError> where P: Default, { let mut new_pun = Punctuated::new(); let mut types_encountered = HashSet::new(); let mut extra_apis = Vec::new(); for arg in pun.into_iter() { new_pun.push(match arg { GenericArgument::Type(t) => { let mut innerty = self.convert_type(t, ns, false)?; types_encountered.extend(innerty.types_encountered.drain()); extra_apis.extend(innerty.extra_apis.drain(..)); GenericArgument::Type(innerty.ty) } _ => arg, }); } Ok(Annotated::new( new_pun, types_encountered, extra_apis, false, )) } fn resolve_typedef<'b>(&'b self, tn: &TypeName) -> Option<&'b Type> { self.typedefs.get(&tn).map(|resolution| match resolution { Type::Path(typ) => { let tn = TypeName::from_type_path(typ); self.resolve_typedef(&tn).unwrap_or(resolution) } _ => resolution, }) } fn convert_ptr_to_reference( &mut self, ptr: TypePtr, ns: &Namespace, ) -> Result<Annotated<Type>, ConvertError> { let mutability = ptr.mutability; let elem = self.convert_boxed_type(ptr.elem, ns, false)?; // TODO - in the future, we should check if this is a rust::Str and throw // a wobbler if not. rust::Str should only be seen _by value_ in C++ // headers; it manifests as &str in Rust but on the C++ side it must // be a plain value. We should detect and abort. Ok(elem.map(|elem| match mutability { Some(_) => Type::Path(parse_quote! { std::pin::Pin < & #mutability #elem > }), None => Type::Reference(parse_quote! { & #elem }), })) } fn add_concrete_type(&self, tyname: &TypeName, rs_definition: &Type) -> UnanalyzedApi { let final_ident = make_ident(tyname.get_final_ident()); let mut fulltypath: Vec<_> = ["bindgen", "root"].iter().map(make_ident).collect(); fulltypath.push(final_ident.clone()); let tynamestring = tyname.to_cpp_name(); UnanalyzedApi { ns: tyname.get_namespace().clone(), id: final_ident.clone(), deps: HashSet::new(), detail: crate::conversion::api::ApiDetail::ConcreteType { ty_details: TypeApiDetails { fulltypath, final_ident, tynamestring, }, additional_cpp: AdditionalNeed::ConcreteTemplatedTypeTypedef( tyname.clone(), Box::new(rs_definition.clone()), ), }, } } fn get_templated_typename( &mut self, rs_definition: &Type, ) -> Result<(TypeName, Option<UnanalyzedApi>), ConvertError> { let count = self.concrete_templates.len(); // We just use this as a hash key, essentially. let cpp_definition = type_to_cpp(rs_definition)?; let e = self.concrete_templates.get(&cpp_definition); match e { Some(tn) => Ok((tn.clone(), None)), None => { let tn = TypeName::new(&Namespace::new(), &format!("AutocxxConcrete{}", count)); self.concrete_templates .insert(cpp_definition.clone(), tn.clone()); let api = self.add_concrete_type(&tn, rs_definition); Ok((tn, Some(api))) } } } }
{ match typ.path.segments.last_mut() { Some(s) if !s.arguments.is_empty() => Some(s), _ => None, } }
user.py
# Copyright © 2019 Province of British Columbia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This manages a User record in the Auth service. A User stores basic information from a KeyCloak user (including the KeyCloak GUID). """ import datetime from flask import current_app from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, and_, or_ from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import relationship from auth_api.utils.enums import AccessType, LoginSource, Status, UserStatus from auth_api.utils.roles import Role from auth_api.utils.user_context import UserContext, user_context from .base_model import BaseModel from .db import db from .membership import Membership as MembershipModel from .org import Org as OrgModel from .user_status_code import UserStatusCode class User(BaseModel): """This is the model for a User.""" __tablename__ = 'users' __versioned__ = { 'exclude': ['modified', 'modified_by_id', 'modified_by', 'created'] } id = Column(Integer, primary_key=True) username = Column('username', String(100), index=True) firstname = Column('first_name', String(200), index=True) lastname = Column('last_name', String(200), index=True) email = Column('email', String(200), index=True) keycloak_guid = Column( 'keycloak_guid', UUID(as_uuid=True), unique=True, nullable=True # bcros users comes with no guid ) is_terms_of_use_accepted = Column(Boolean(), default=False, nullable=True) terms_of_use_accepted_version = Column( ForeignKey('documents.version_id'), nullable=True ) # a type for the user to identify what kind of user it is..ie anonymous , bcsc etc ..similar to login source type = Column('type', String(200), nullable=True) status = Column(ForeignKey('user_status_codes.id')) idp_userid = Column('idp_userid', String(256), index=True) login_source = Column('login_source', String(200), nullable=True) login_time = Column(DateTime, default=None, nullable=True) contacts = relationship('ContactLink', primaryjoin='User.id == ContactLink.user_id', lazy='select') orgs = relationship('Membership', primaryjoin='and_(User.id == Membership.user_id, or_(Membership.status == ' + str( Status.ACTIVE.value) + ', Membership.status == ' + str( Status.PENDING_APPROVAL.value) + '))', lazy='select') # noqa:E127 terms_of_use_version = relationship('Documents', foreign_keys=[terms_of_use_accepted_version], uselist=False, lazy='select') user_status = relationship('UserStatusCode', foreign_keys=[status], lazy='subquery') @classmethod def find_by_username(cls, username): """Return the first user with the provided username.""" return cls.query.filter_by(username=username).first() @classmethod @user_context def find_by_jwt_token(cls, **kwargs): """Find an existing user by the keycloak GUID and (idpUserId is null or from token) in the provided token.""" user_from_context: UserContext = kwargs['user_context'] return db.session.query(User).filter( and_(User.keycloak_guid == user_from_context.sub, or_(User.idp_userid == user_from_context.token_info.get('idp_userid', None), User.idp_userid.is_(None)))).one_or_none() @classmethod @user_context def create_from_jwt_token(cls, first_name: str, last_name: str, **kwargs): """Create a User from the provided JWT.""" user_from_context: UserContext = kwargs['user_context'] token = user_from_context.token_info if token: user = User( username=user_from_context.user_name, firstname=first_name, lastname=last_name, email=token.get('email', None), keycloak_guid=user_from_context.sub, created=datetime.datetime.now(), login_source=user_from_context.login_source, status=UserStatusCode.get_default_type(), idp_userid=token.get('idp_userid', None), login_time=datetime.datetime.now(), type=cls._get_type(user_from_context=user_from_context) ) current_app.logger.debug( 'Creating user from JWT:{}; User:{}'.format(token, user) ) user.save() return user return None @classmethod @user_context def update_from_jwt_token(cls, user, # pylint:disable=too-many-arguments first_name: str, last_name: str, is_login: bool = False, **kwargs): """Update a User from the provided JWT.""" user_from_context: UserContext = kwargs['user_context'] token = user_from_context.token_info if not token or not user: return None # Do not save if nothing has been changed # pylint: disable=too-many-boolean-expressions if not is_login \ and (user.username == user_from_context.user_name or user.username) \ and user.firstname == first_name \ and user.lastname == last_name \ and user.email == token.get('email', user.email) \ and (str(user.keycloak_guid) == user_from_context.sub or user.keycloak_guid) \ and user.status == UserStatus.ACTIVE.value \ and (user.login_source == user_from_context.login_source or user.login_source) \ and user.idp_userid == token.get('idp_userid', None): return user current_app.logger.debug( 'Updating user from JWT:{}; User:{}'.format(token, user) ) user.username = user_from_context.user_name or user.username user.firstname = first_name user.lastname = last_name user.email = token.get('email', user.email) user.modified = datetime.datetime.now() if token.get('accessType', None) == AccessType.ANONYMOUS.value: # update kcguid for anonymous users user.keycloak_guid = user_from_context.sub or user.keycloak_guid # If this user is marked as Inactive, this login will re-activate them user.status = UserStatus.ACTIVE.value user.login_source = user_from_context.login_source or user.login_source user.type = cls._get_type(user_from_context) # If this is a request during login, update login_time if is_login: user.login_time = datetime.datetime.now() user.idp_userid = token.get('idp_userid') cls.commit() return user @classmethod def find_users(cls, first_name, last_name, email): """Return a set of users with either the given username or the given email.""" # TODO: This needs to be improved for scalability. Paging large datasets etc. if first_name == '' and last_name == '' and email == '': return cls.query.all() return cls.query.filter(or_(cls.firstname == first_name, cls.lastname == last_name, cls.email == email)).all() @classmethod @user_context def update_terms_of_use(cls, is_terms_accepted, terms_of_use_version, **kwargs): """Update the terms of service for the user.""" user_from_context: UserContext = kwargs['user_context'] if user_from_context.token_info: user = cls.find_by_jwt_token() user.is_terms_of_use_accepted = is_terms_accepted user.terms_of_use_accepted_version = terms_of_use_version current_app.logger.debug( 'Updating users Terms of use is_terms_accepted:{}; terms_of_use_version:{}'.format( is_terms_accepted, terms_of_use_version) ) cls.save(user) return user return None @classmethod def find_users_by_org_id_by_status_by_roles(cls, org_id, roles, status=Status.ACTIVE.value): """Find all members of the org with a status.""" return db.session.query(User). \ join(MembershipModel, (User.id == MembershipModel.user_id) & (MembershipModel.status == status) & (MembershipModel.membership_type_code.in_(roles))). \ join(OrgModel).filter(OrgModel.id == org_id).all() def delete(self): """Users cannot be deleted so intercept the ORM by just returning.""" return self @classmethod def _
cls, user_from_context: UserContext) -> str: """Return type of the user from the token info.""" user_type: str = None if user_from_context.roles: if Role.ANONYMOUS_USER.value in user_from_context.roles \ or user_from_context.login_source == LoginSource.BCROS.value: user_type = Role.ANONYMOUS_USER.name elif Role.GOV_ACCOUNT_USER.value in user_from_context.roles: user_type = Role.GOV_ACCOUNT_USER.name elif Role.PUBLIC_USER.value in user_from_context.roles \ or user_from_context.login_source in [LoginSource.BCEID.value, LoginSource.BCSC.value]: user_type = Role.PUBLIC_USER.name elif user_from_context.is_staff(): user_type = Role.STAFF.name elif user_from_context.is_system(): user_type = Role.SYSTEM.name return user_type
get_type(
main.rs
use type_constructor::*; fn
() { types! { #[ derive( Debug ) ] single MySingle : < T : Copy >; } let x = MySingle( 13 ); dbg!( x ); }
main
basic.rs
use sprawl::prelude::*; fn main() -> Result<(), Error> { let mut sprawl = Sprawl::new(); let child = sprawl.new_node( Style { size: Size { width: Dimension::Percent(0.5), height: Dimension::Auto }, ..Default::default() }, &[], )?; let node = sprawl.new_node( Style { size: Size { width: Dimension::Points(100.0), height: Dimension::Points(100.0) }, justify_content: JustifyContent::Center, ..Default::default() }, &[child], )?; sprawl.compute_layout(node, Size { height: Number::Defined(100.0), width: Number::Defined(100.0) })?;
println!("node: {:#?}", sprawl.layout(node)?); println!("child: {:#?}", sprawl.layout(child)?); Ok(()) }
// or just use undefined for 100 x 100 // sprawl.compute_layout(node, Size::undefined())?;
modules.py
# coding: utf-8 import torch from torch import nn import math import numpy as np from torch.nn import functional as F def position_encoding_init(n_position, d_pos_vec, position_rate=1.0, sinusoidal=True): ''' Init the sinusoid position encoding table ''' # keep dim 0 for padding token position encoding zero vector position_enc = np.array([ [position_rate * pos / np.power(10000, 2 * (i // 2) / d_pos_vec) for i in range(d_pos_vec)] if pos != 0 else np.zeros(d_pos_vec) for pos in range(n_position)]) position_enc = torch.from_numpy(position_enc).float() if sinusoidal: position_enc[1:, 0::2] = torch.sin(position_enc[1:, 0::2]) # dim 2i position_enc[1:, 1::2] = torch.cos(position_enc[1:, 1::2]) # dim 2i+1 return position_enc def sinusoidal_encode(x, w): y = w * x y[1:, 0::2] = torch.sin(y[1:, 0::2].clone()) y[1:, 1::2] = torch.cos(y[1:, 1::2].clone()) return y class SinusoidalEncoding(nn.Embedding): def __init__(self, num_embeddings, embedding_dim, *args, **kwargs): super(SinusoidalEncoding, self).__init__(num_embeddings, embedding_dim, padding_idx=0, *args, **kwargs) self.weight.data = position_encoding_init(num_embeddings, embedding_dim, position_rate=1.0, sinusoidal=False) def forward(self, x, w=1.0): isscaler = np.isscalar(w) assert self.padding_idx is not None if isscaler or w.size(0) == 1: weight = sinusoidal_encode(self.weight, w) return F.embedding( x, weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse) else: # TODO: cannot simply apply for batch # better to implement efficient function pe = [] for batch_idx, we in enumerate(w): weight = sinusoidal_encode(self.weight, we) pe.append(F.embedding( x[batch_idx], weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse)) pe = torch.stack(pe) return pe class GradMultiply(torch.autograd.Function): @staticmethod def forward(ctx, x, scale): ctx.scale = scale res = x.new(x) ctx.mark_shared_storage((x, res)) return res @staticmethod def backward(ctx, grad): return grad * ctx.scale, None def Linear(in_features, out_features, dropout=0): """Weight-normalized Linear layer (input: N x T x C)""" m = nn.Linear(in_features, out_features) m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features)) m.bias.data.zero_() return nn.utils.weight_norm(m) def Embedding(num_embeddings, embedding_dim, padding_idx, std=0.01): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) m.weight.data.normal_(0, std) return m def Conv1d(in_channels, out_channels, kernel_size, dropout=0, std_mul=4.0, **kwargs): from .conv import Conv1d m = Conv1d(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) m.weight.data.normal_(mean=0, std=std) m.bias.data.zero_() return nn.utils.weight_norm(m) def ConvTranspose1d(in_channels, out_channels, kernel_size, dropout=0, std_mul=1.0, **kwargs): m = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((std_mul * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) m.weight.data.normal_(mean=0, std=std) m.bias.data.zero_() return nn.utils.weight_norm(m) class Conv1dGLU(nn.Module): """(Dilated) Conv1d + Gated linear unit + (optionally) speaker embedding """ def __init__(self, n_speakers, speaker_embed_dim, in_channels, out_channels, kernel_size, dropout, padding=None, dilation=1, causal=False, residual=False, *args, **kwargs): super(Conv1dGLU, self).__init__() self.dropout = dropout self.residual = residual if padding is None: # no future time stamps available if causal: padding = (kernel_size - 1) * dilation else: padding = (kernel_size - 1) // 2 * dilation self.causal = causal self.conv = Conv1d(in_channels, 2 * out_channels, kernel_size, dropout=dropout, padding=padding, dilation=dilation, *args, **kwargs) if n_speakers > 1: self.speaker_proj = Linear(speaker_embed_dim, out_channels) else: self.speaker_proj = None def forward(self, x, speaker_embed=None): return self._forward(x, speaker_embed, False) def incremental_forward(self, x, speaker_embed=None): return self._forward(x, speaker_embed, True) def _forward(self, x, speaker_embed, is_incremental): residual = x x = F.dropout(x, p=self.dropout, training=self.training) if is_incremental: splitdim = -1 x = self.conv.incremental_forward(x) else: splitdim = 1 x = self.conv(x) # remove future time steps x = x[:, :, :residual.size(-1)] if self.causal else x a, b = x.split(x.size(splitdim) // 2, dim=splitdim) if self.speaker_proj is not None: softsign = F.softsign(self.speaker_proj(speaker_embed)) # Since conv layer assumes BCT, we need to transpose softsign = softsign if is_incremental else softsign.transpose(1, 2) a = a + softsign x = a * torch.sigmoid(b) return (x + residual) * math.sqrt(0.5) if self.residual else x def clear_buffer(self): self.conv.clear_buffer() class HighwayConv1d(nn.Module): """Weight normzlized Conv1d + Highway network (support incremental forward) """ def __init__(self, in_channels, out_channels, kernel_size=1, padding=None, dilation=1, causal=False, dropout=0, std_mul=None, glu=False): super(HighwayConv1d, self).__init__() if std_mul is None: std_mul = 4.0 if glu else 1.0 if padding is None: # no future time stamps available
self.causal = causal self.dropout = dropout self.glu = glu self.conv = Conv1d(in_channels, 2 * out_channels, kernel_size=kernel_size, padding=padding, dilation=dilation, dropout=dropout, std_mul=std_mul) def forward(self, x): return self._forward(x, False) def incremental_forward(self, x): return self._forward(x, True) def _forward(self, x, is_incremental): """Forward Args: x: (B, in_channels, T) returns: (B, out_channels, T) """ residual = x x = F.dropout(x, p=self.dropout, training=self.training) if is_incremental: splitdim = -1 x = self.conv.incremental_forward(x) else: splitdim = 1 x = self.conv(x) # remove future time steps x = x[:, :, :residual.size(-1)] if self.causal else x if self.glu: x = F.glu(x, dim=splitdim) return (x + residual) * math.sqrt(0.5) else: a, b = x.split(x.size(splitdim) // 2, dim=splitdim) T = torch.sigmoid(b) return (T * a + (1 - T) * residual) def clear_buffer(self): self.conv.clear_buffer() def get_mask_from_lengths(memory, memory_lengths): """Get mask tensor from list of length Args: memory: (batch, max_time, dim) memory_lengths: array like """ mask = memory.data.new(memory.size(0), memory.size(1)).byte().zero_() for idx, l in enumerate(memory_lengths): mask[idx][:l] = 1 return ~mask
if causal: padding = (kernel_size - 1) * dilation else: padding = (kernel_size - 1) // 2 * dilation
solution.py
def
(square): removeStarting = lambda x: [y[:-1] for y in x[1:]] corner = lambda x: x[0]+[y[-1] for y in x[1:]] result =[] n = len(square) if n == 0: return [] for i in range(n): if i % 2 ==0: result = result + corner(square) else: result = result + corner(square)[::-1] square = removeStarting(square) return result
corner_fill
create_forward_request_builder.go
package createforward import ( ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9 "github.com/microsoft/kiota/abstractions/go" i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization" i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87 "github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph" ) // CreateForwardRequestBuilder builds and executes requests for operations under \me\mailFolders\{mailFolder-id}\messages\{message-id}\microsoft.graph.createForward type CreateForwardRequestBuilder struct { // Path parameters for the request pathParameters map[string]string; // The request adapter to use to execute the requests. requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter; // Url template to use to build the URL for the current request builder urlTemplate string; } // CreateForwardRequestBuilderPostOptions options for Post type CreateForwardRequestBuilderPostOptions struct { // Body *CreateForwardRequestBody; // Request headers H map[string]string; // Request options O []ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestOption; // Response handler to use in place of the default response handling provided by the core service ResponseHandler ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ResponseHandler; } // CreateForwardResponse union type wrapper for classes message type CreateForwardResponse struct { // Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. additionalData map[string]interface{}; // Union type representation for type message message *i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.Message; } // NewCreateForwardResponse instantiates a new createForwardResponse and sets the default values. func
()(*CreateForwardResponse) { m := &CreateForwardResponse{ } m.SetAdditionalData(make(map[string]interface{})); return m } // GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. func (m *CreateForwardResponse) GetAdditionalData()(map[string]interface{}) { if m == nil { return nil } else { return m.additionalData } } // GetMessage gets the message property value. Union type representation for type message func (m *CreateForwardResponse) GetMessage()(*i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.Message) { if m == nil { return nil } else { return m.message } } // GetFieldDeserializers the deserialization information for the current model func (m *CreateForwardResponse) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) { res := make(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) res["message"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.NewMessage() }) if err != nil { return err } if val != nil { m.SetMessage(val.(*i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.Message)) } return nil } return res } func (m *CreateForwardResponse) IsNil()(bool) { return m == nil } // Serialize serializes information the current object func (m *CreateForwardResponse) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) { { err := writer.WriteObjectValue("message", m.GetMessage()) if err != nil { return err } } { err := writer.WriteAdditionalData(m.GetAdditionalData()) if err != nil { return err } } return nil } // SetAdditionalData sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. func (m *CreateForwardResponse) SetAdditionalData(value map[string]interface{})() { if m != nil { m.additionalData = value } } // SetMessage sets the message property value. Union type representation for type message func (m *CreateForwardResponse) SetMessage(value *i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.Message)() { if m != nil { m.message = value } } // NewCreateForwardRequestBuilderInternal instantiates a new CreateForwardRequestBuilder and sets the default values. func NewCreateForwardRequestBuilderInternal(pathParameters map[string]string, requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter)(*CreateForwardRequestBuilder) { m := &CreateForwardRequestBuilder{ } m.urlTemplate = "{+baseurl}/me/mailFolders/{mailFolder_id}/messages/{message_id}/microsoft.graph.createForward"; urlTplParams := make(map[string]string) for idx, item := range pathParameters { urlTplParams[idx] = item } m.pathParameters = pathParameters; m.requestAdapter = requestAdapter; return m } // NewCreateForwardRequestBuilder instantiates a new CreateForwardRequestBuilder and sets the default values. func NewCreateForwardRequestBuilder(rawUrl string, requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter)(*CreateForwardRequestBuilder) { urlParams := make(map[string]string) urlParams["request-raw-url"] = rawUrl return NewCreateForwardRequestBuilderInternal(urlParams, requestAdapter) } // CreatePostRequestInformation invoke action createForward func (m *CreateForwardRequestBuilder) CreatePostRequestInformation(options *CreateForwardRequestBuilderPostOptions)(*ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestInformation, error) { requestInfo := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.NewRequestInformation() requestInfo.UrlTemplate = m.urlTemplate requestInfo.PathParameters = m.pathParameters requestInfo.Method = ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.POST requestInfo.SetContentFromParsable(m.requestAdapter, "application/json", options.Body) if options != nil && options.H != nil { requestInfo.Headers = options.H } if options != nil && len(options.O) != 0 { err := requestInfo.AddRequestOptions(options.O...) if err != nil { return nil, err } } return requestInfo, nil } // Post invoke action createForward func (m *CreateForwardRequestBuilder) Post(options *CreateForwardRequestBuilderPostOptions)(*CreateForwardResponse, error) { requestInfo, err := m.CreatePostRequestInformation(options); if err != nil { return nil, err } res, err := m.requestAdapter.SendAsync(*requestInfo, func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewCreateForwardResponse() }, nil, nil) if err != nil { return nil, err } return res.(*CreateForwardResponse), nil }
NewCreateForwardResponse
mssql.py
import re from .._compat import PY2, iteritems, integer_types, to_unicode, long from .._globals import IDENTITY from .base import SQLAdapter from . import adapters, with_connection_or_raise class Slicer(object): def rowslice(self, rows, minimum=0, maximum=None): if maximum is None: return rows[minimum:] return rows[minimum:maximum] class MSSQL(SQLAdapter): dbengine = 'mssql' drivers = ('pyodbc',) REGEX_DSN = '^.+$' REGEX_URI = \ '^(?P<user>[^:@]+)(:(?P<password>[^@]*))?' \ r'@(?P<host>[^:/]+|\[[^\]]+\])(:(?P<port>\d+))?' \ '/(?P<db>[^?]+)' \ r'(\?(?P<urlargs>.*))?$' REGEX_ARG_VAL = '(?P<argkey>[^=]+)=(?P<argvalue>[^&]*)' def __init__(self, db, uri, pool_size=0, folder=None, db_codec='UTF-8', credential_decoder=IDENTITY, driver_args={}, adapter_args={}, do_connect=True, srid=4326, after_connection=None): self.srid = srid super(MSSQL, self).__init__( db, uri, pool_size, folder, db_codec, credential_decoder, driver_args, adapter_args, do_connect, after_connection) def _initialize_(self, do_connect): super(MSSQL, self)._initialize_(do_connect) ruri = self.uri.split('://', 1)[1] if '@' not in ruri: m = re.match(self.REGEX_DSN, ruri) if not m: raise SyntaxError("Invalid URI string in DAL") self.dsn = m.group() else: m = re.match(self.REGEX_URI, ruri) if not m: raise SyntaxError( "Invalid URI string in DAL: %s" % self.uri) user = self.credential_decoder(m.group('user')) password = self.credential_decoder(m.group('password')) if password is None: password = '' host = m.group('host') db = m.group('db') port = m.group('port') or '1433' # Parse the optional url name-value arg pairs after the '?' # (in the form of arg1=value1&arg2=value2&...) # (drivers like FreeTDS insist on uppercase parameter keys) argsdict = {'DRIVER': '{SQL Server}'} urlargs = m.group('urlargs') or '' for argmatch in re.finditer(self.REGEX_ARG_VAL, urlargs): argsdict[str(argmatch.group('argkey')).upper()] = \ argmatch.group('argvalue') urlargs = ';'.join([ '%s=%s' % (ak, av) for (ak, av) in iteritems(argsdict)]) self.dsn = 'SERVER=%s;PORT=%s;DATABASE=%s;UID=%s;PWD=%s;%s' \ % (host, port, db, user, password, urlargs) def connector(self): return self.driver.connect(self.dsn, **self.driver_args) def lastrowid(self, table): self.execute('SELECT SCOPE_IDENTITY();') return long(self.cursor.fetchone()[0]) @adapters.register_for('mssql') class MSSQL1(MSSQL, Slicer): pass @adapters.register_for('mssql3') class
(MSSQL): pass @adapters.register_for('mssql4') class MSSQL4(MSSQL): pass class MSSQLN(MSSQL): def represent(self, obj, field_type): rv = super(MSSQLN, self).represent(obj, field_type) if field_type in ('string', 'text', 'json') and rv.startswith("'"): rv = 'N' + rv return rv @with_connection_or_raise def execute(self, *args, **kwargs): if PY2: args = list(args) args[0] = to_unicode(args[0]) return super(MSSQLN, self).execute(*args, **kwargs) @adapters.register_for('mssqln', 'mssql2') class MSSQL1N(MSSQLN, Slicer): pass @adapters.register_for('mssql3n') class MSSQL3N(MSSQLN): pass @adapters.register_for('mssql4n') class MSSQL4N(MSSQLN): pass @adapters.register_for('vertica') class Vertica(MSSQL1): def lastrowid(self, table): self.execute('SELECT SCOPE_IDENTITY();') return long(self.cursor.fetchone()[0]) @adapters.register_for('sybase') class Sybase(MSSQL1): dbengine = 'sybase' def _initialize_(self, do_connect): super(MSSQL, self)._initialize_(do_connect) ruri = self.uri.split('://', 1)[1] if '@' not in ruri: m = re.match(self.REGEX_DSN, ruri) if not m: raise SyntaxError("Invalid URI string in DAL") dsn = m.group() else: m = re.match(self.REGEX_URI, ruri) if not m: raise SyntaxError( "Invalid URI string in DAL: %s" % self.uri) user = self.credential_decoder(m.group('user')) password = self.credential_decoder(m.group('password')) if password is None: password = '' host = m.group('host') db = m.group('db') port = m.group('port') or '1433' self.dsn = 'sybase:host=%s:%s;dbname=%s' % (host, port, db) self.driver_args.update( user=self.credential_decoder(user), passwd=self.credential_decoder(password))
MSSQL3
option.go
package lib import ( "errors" "fmt" "strconv" "strings" goopt "github.com/droundy/goopt" ) type optionType int // option types, only support three kinds now const ( OptionTypeString optionType = iota OptionTypeInt64 OptionTypeFlagTrue OptionTypeAlternative ) // Option describe the component of a option type Option struct { name string nameAlias string def string optionType optionType minVal string // empty means no check, for OptionTypeAlternative, minVal is the alternative values connected by '/', eg: CN/EN maxVal string // empty means no check, for OptionTypeAlternative, maxVal is empty helpChinese string helpEnglish string } // LEnglishLanguage is the lower case of EnglishLanguage var LEnglishLanguage = strings.ToLower(EnglishLanguage) // OptionMap is a collection of ossutil supported options var OptionMap = map[string]Option{ OptionConfigFile: Option{"-c", "--config-file", "", OptionTypeString, "", "", "ossutil工具的配置文件路径,ossutil启动时从配置文件读取配置,在config命令中,ossutil将配置写入该文件。", "Path of ossutil configuration file, where to dump config in config command, or to load config in other commands that need credentials."}, OptionEndpoint: Option{"-e", "--endpoint", "", OptionTypeString, "", "", fmt.Sprintf("ossutil工具的基本endpoint配置(该选项值会覆盖配置文件中的相应设置),注意其必须为一个二级域名。"), fmt.Sprintf("Base endpoint for oss endpoint(Notice that the value of the option will cover the value in config file). Take notice that it should be second-level domain(SLD).")}, OptionAccessKeyID: Option{"-i", "--access-key-id", "", OptionTypeString, "", "", "访问oss使用的AccessKeyID(该选项值会覆盖配置文件中的相应设置)。", "AccessKeyID while access oss(Notice that the value of the option will cover the value in config file)."}, OptionAccessKeySecret: Option{"-k", "--access-key-secret", "", OptionTypeString, "", "", "访问oss使用的AccessKeySecret(该选项值会覆盖配置文件中的相应设置)。", "AccessKeySecret while access oss(Notice that the value of the option will cover the value in config file)."}, OptionSTSToken: Option{"-t", "--sts-token", "", OptionTypeString, "", "", "访问oss使用的STSToken(该选项值会覆盖配置文件中的相应设置),非必须设置项。", "STSToken while access oss(Notice that the value of the option will cover the value in config file), not necessary."}, OptionLimitedNum: Option{"", "--limited-num", strconv.Itoa(DefaultLimitedNum), OptionTypeInt64, strconv.FormatInt(MinLimitedNum, 10), "", "返回结果的最大个数。", "the limited number of return results."}, OptionMarker: Option{"", "--marker", "", OptionTypeString, "", "", "列举Buckets时的marker,或列举objects或Multipart Uploads时的key marker, 或者其他有需要marker的地方。", "the marker of bucket when list buckets, or the marker of key when list object or Multipart Uploads, Or other places where a marker is needed"}, OptionUploadIDMarker: Option{"", "--upload-id-marker", "", OptionTypeString, "", "", "列举Multipart Uploads时的uploadID marker。", "the marker of object when list object or Multipart Uploads."}, OptionACL: Option{"", "--acl", "", OptionTypeString, "", "", "acl信息的配置。", "acl information."}, OptionShortFormat: Option{"-s", "--short-format", "", OptionTypeFlagTrue, "", "", "显示精简格式,如果未指定该选项,默认显示长格式。", "Show by short format, if the option is not specified, show long format by default."}, OptionDirectory: Option{"-d", "--directory", "", OptionTypeFlagTrue, "", "", "返回当前目录下的文件和子目录,而非递归显示所有子目录下的所有object。", "Return matching subdirectory names instead of contents of the subdirectory."}, OptionMultipart: Option{"-m", "--multipart", "", OptionTypeFlagTrue, "", "", "指定操作的对象为bucket中未完成的Multipart事件,而非默认情况下的object。", "Indicate that the subject of the command are uncompleted Multipart Uploads, instead of objects(which is the subject in default situation."}, OptionAllType: Option{"-a", "--all-type", "", OptionTypeFlagTrue, "", "", "指定操作的对象为bucket中的object和未完成的Multipart事件。", "Indicate that the subject of the command contains both objects and uncompleted Multipart Uploads."}, OptionRecursion: Option{"-r", "--recursive", "", OptionTypeFlagTrue, "", "", "递归进行操作。对于支持该选项的命令,当指定该选项时,命令会对bucket下所有符合条件的objects进行操作,否则只对url中指定的单个object进行操作。", "operate recursively, for those commands which support the option, when use them, if the option is specified, the command will operate on all match objects under the bucket, else we will search the specified object and operate on the single object."}, OptionBucket: Option{"-b", "--bucket", "", OptionTypeFlagTrue, "", "", "对bucket进行操作,该选项用于确认操作作用于bucket", "the option used to make sure the operation will operate on bucket"}, OptionStorageClass: Option{"", "--storage-class", DefaultStorageClass, OptionTypeAlternative, fmt.Sprintf("%s/%s/%s/%s", StorageStandard, StorageIA, StorageArchive, StorageColdArchive), "", fmt.Sprintf("设置对象的存储方式,默认值:%s,取值范围:%s/%s/%s/%s。", DefaultStorageClass, StorageStandard, StorageIA, StorageArchive, StorageColdArchive), fmt.Sprintf("set the storage class of bucket(default: %s), value range is: %s/%s/%s/%s.", DefaultStorageClass, StorageStandard, StorageIA, StorageArchive, StorageColdArchive)}, OptionForce: Option{"-f", "--force", "", OptionTypeFlagTrue, "", "", "强制操作,不进行询问提示。", "operate silently without asking user to confirm the operation."}, OptionUpdate: Option{"-u", "--update", "", OptionTypeFlagTrue, "", "", "更新操作", "update"}, OptionDelete: Option{"", "--delete", "", OptionTypeFlagTrue, "", "", "删除操作", "delete"}, OptionOutputDir: Option{"", "--output-dir", DefaultOutputDir, OptionTypeString, "", "", fmt.Sprintf("指定输出文件所在的目录,输出文件目前包含:cp命令批量拷贝文件出错时所产生的report文件(关于report文件更多信息,请参考cp命令帮助)。默认值为:当前目录下的%s目录。", DefaultOutputDir), fmt.Sprintf("The option specify the directory to place output file in, output file contains: report file generated by cp command when error happens of batch copy operation(for more information about report file, see help of cp command). The default value of the option is: %s directory in current directory.", DefaultOutputDir)}, OptionBigFileThreshold: Option{"", "--bigfile-threshold", strconv.FormatInt(DefaultBigFileThreshold, 10), OptionTypeInt64, strconv.FormatInt(MinBigFileThreshold, 10), strconv.FormatInt(MaxBigFileThreshold, 10), fmt.Sprintf("开启大文件断点续传的文件大小阈值,默认值:%dM,取值范围:%dB-%dB", DefaultBigFileThreshold/1048576, MinBigFileThreshold, MaxBigFileThreshold), fmt.Sprintf("the threshold of file size, the file size larger than the threshold will use resume upload or download(default: %d), value range is: %d-%d", DefaultBigFileThreshold, MinBigFileThreshold, MaxBigFileThreshold)}, OptionPartSize: Option{"", "--part-size", strconv.FormatInt(DefaultPartSize, 10), OptionTypeInt64, strconv.FormatInt(MinPartSize, 10), strconv.FormatInt(MaxPartSize, 10), fmt.Sprintf("分片大小,单位为Byte,默认情况下ossutil根据文件大小自行计算合适的分片大小值。如果有特殊需求或者需要性能调优,可以设置该值,取值范围:%d-%d(Byte)", MinPartSize, MaxPartSize), fmt.Sprintf("Part size, the unit is: Byte, in default situation, ossutil will calculate the suitable part size according to file size. The option is useful when user has special needs or user need to performance tuning, the value range is: %d-%d(Byte)", MinPartSize, MaxPartSize)}, OptionDisableCRC64: Option{"", "--disable-crc64", "", OptionTypeFlagTrue, "", "", "该选项关闭crc64,默认情况下,ossutil进行数据传输都打开crc64校验。", "Disable crc64, in default situation, ossutil open crc64 check when transmit data."}, OptionCheckpointDir: Option{"", "--checkpoint-dir", CheckpointDir, OptionTypeString, "", "", fmt.Sprintf("checkpoint目录的路径(默认值为:%s),断点续传时,操作失败ossutil会自动创建该目录,并在该目录下记录checkpoint信息,操作成功会删除该目录。如果指定了该选项,请确保所指定的目录可以被删除。", CheckpointDir), fmt.Sprintf("Path of checkpoint directory(default:%s), the directory is used in resume upload or download, when operate failed, ossutil will create the directory automatically, and record the checkpoint information in the directory, when the operation is succeed, the directory will be removed, so when specify the option, please make sure the directory can be removed.", CheckpointDir)}, OptionSnapshotPath: Option{"", "--snapshot-path", "", OptionTypeString, "", "", "该选项用于在某些场景下加速增量上传批量文件或者增量下载批量object。在cp上传文件或者下载object时使用该选项,ossutil在指定的目录下生成快照文件,记录文件上传或者object下载的快照信息,在下一次指定该选项上传或下载时,ossutil会读取指定目录下的快照信息进行增量上传或者下载。用户指定的snapshot目录必须为本地文件系统上的可写目录,若该目录不存在,ossutil会创建该文件用于记录快照信息,如果该目录已存在,ossutil会读取里面的快照信息,根据快照信息进行增量上传(只上传上次未成功上传的文件和本地进行过修改的文件)或者增量下载(只下载上次未成功下载的object和修改过的object),并更新快照信息。注意:该选项在本地记录了成功上传的文件的本地lastModifiedTime或者记录了下载object的lastModifiedTime,从而在下次上传或者下载时通过比较lastModifiedTime来决定是否跳过相同文件的上传或者跳过相同的object下载。当使用该选项上传时,请确保两次上传期间没有其他用户更改了oss上的对应object。当不满足该场景时,如果想要增量上传批量文件,请使用--update选项。ossutil不会主动删除snapshot-path下的快照信息,当用户确定快照信息无用时,请用户及时自行删除snapshot-path。", "This option is used to accelerate the incremental upload of batch files or download objects in certain scenarios. If you use the option when upload files or download objects, ossutil will generate files to record the snapshot information in the specified directory. When the next time you upload files or download objects with the option, ossutil will read the snapshot information under the specified directory for incremental upload or incremental download. The snapshot-path you specified must be a local file system directory can be written in, if the directory does not exist, ossutil creates the files for recording snapshot information, else ossutil will read snapshot information from the path for incremental upload(ossutil will only upload the files which haven't not been successfully uploaded to oss or been locally modified) or incremental download(ossutil will only download the objects which have not been successfully downloaded or have been modified), and update the snapshot information to the directory. Note: The option record the lastModifiedTime of local files which have been successfully uploaded in local file system or lastModifiedTime of objects which have been successfully downloaded, and compare the lastModifiedTime of local files or objects in the next cp to decided whether to skip the file or object. If you use the option to achieve incremental upload, please make sure no other user modified the corresponding object in oss during the two uploads. If you can not guarantee the scenarios, please use --update option to achieve incremental upload. In addition, ossutil does not automatically delete snapshot-path snapshot information, in order to avoid too much snapshot information, when the snapshot information is useless, please clean up your own snapshot-path on your own immediately."}, OptionRetryTimes: Option{"", "--retry-times", strconv.Itoa(RetryTimes), OptionTypeInt64, strconv.FormatInt(MinRetryTimes, 10), strconv.FormatInt(MaxRetryTimes, 10), fmt.Sprintf("当错误发生时的重试次数,默认值:%d,取值范围:%d-%d", RetryTimes, MinRetryTimes, MaxRetryTimes), fmt.Sprintf("retry times when fail(default: %d), value range is: %d-%d", RetryTimes, MinRetryTimes, MaxRetryTimes)}, OptionRoutines: Option{"-j", "--jobs", strconv.Itoa(Routines), OptionTypeInt64, strconv.FormatInt(MinRoutines, 10), strconv.FormatInt(MaxRoutines, 10), fmt.Sprintf("多文件操作时的并发任务数,默认值:%d,取值范围:%d-%d", Routines, MinRoutines, MaxRoutines), fmt.Sprintf("amount of concurrency tasks between multi-files(default: %d), value range is: %d-%d", Routines, MinRoutines, MaxRoutines)}, OptionParallel: Option{"", "--parallel", "", OptionTypeInt64, strconv.FormatInt(MinParallel, 10), strconv.FormatInt(MaxParallel, 10), fmt.Sprintf("单文件内部操作的并发任务数,取值范围:%d-%d, 默认将由ossutil根据操作类型和文件大小自行决定。", MinRoutines, MaxRoutines), fmt.Sprintf("amount of concurrency tasks when work with a file, value range is: %d-%d, by default the value will be decided by ossutil intelligently.", MinRoutines, MaxRoutines)}, OptionRange: Option{"", "--range", "", OptionTypeString, "", "", "下载文件时,指定文件下载的范围,格式为:3-9或3-或-9", "the range when download objects, the form is like: 3-9 or 3- or -9"}, OptionEncodingType: Option{"", "--encoding-type", "", OptionTypeAlternative, URLEncodingType, "", fmt.Sprintf("输入或者输出的object名或文件名的编码方式,目前只支持url encode,即指定该选项时,取值范围为:%s,如果不指定该选项,则表示object名或文件名未经过编码。bucket名不支持url encode。注意,如果指定了该选项,则形如oss://bucket/object的cloud_url,输入形式为:oss://bucket/url_encode(object),其中oss://bucket/字符串不需要编码。", URLEncodingType), fmt.Sprintf("the encoding type of object name or file name that user inputs or outputs, currently ossutil only supports url encode, which means the value range of the option is: %s, if you do not specify the option, it means the object name or file name that user inputed or outputed was not encoded. bucket name does not support url encode. Note, if the option is specified, the cloud_url like: oss://bucket/object should be inputted as: oss://bucket/url_encode(object), the string: oss://bucket/ should not be url encoded.", URLEncodingType)}, OptionInclude: Option{"", "--include", DefaultNonePattern, OptionTypeString, "", "", fmt.Sprintf("包含对象匹配模式,如:*.jpg"), fmt.Sprintf("Include Pattern of key, e.g., *.jpg")}, OptionExclude: Option{"", "--exclude", DefaultNonePattern, OptionTypeString, "", "", fmt.Sprintf("不包含对象匹配模式,如:*.txt"), fmt.Sprintf("Exclude Pattern of key, e.g., *.txt")}, OptionMeta: Option{"", "--meta", "", OptionTypeString, "", "", fmt.Sprintf("设置object的meta为[header:value#header:value...],如:Cache-Control:no-cache#Content-Encoding:gzip"), fmt.Sprintf("Set object meta as [header:value#header:value...], e.g., Cache-Control:no-cache#Content-Encoding:gzip")}, OptionTimeout: Option{"", "--timeout", strconv.FormatInt(DefaultTimeout, 10), OptionTypeInt64, strconv.FormatInt(MinTimeout, 10), strconv.FormatInt(MaxTimeout, 10), fmt.Sprintf("签名url的超时时间,单位为秒,默认值为:%d,取值范围:%d-%d", DefaultTimeout, MinTimeout, MaxTimeout), fmt.Sprintf("time out of signurl, the unit is: s, default value is %d, the value range is: %d-%d", DefaultTimeout, MinTimeout, MaxTimeout)}, OptionLanguage: Option{"-L", "--language", DefaultLanguage, OptionTypeAlternative, fmt.Sprintf("%s/%s", ChineseLanguage, EnglishLanguage), "", fmt.Sprintf("设置ossutil工具的语言,默认值:%s,取值范围:%s/%s,若设置成\"%s\",请确保您的系统编码为UTF-8。", DefaultLanguage, ChineseLanguage, EnglishLanguage, ChineseLanguage), fmt.Sprintf("set the language of ossutil(default: %s), value range is: %s/%s, if you set it to \"%s\", please make sure your system language is UTF-8.", DefaultLanguage, ChineseLanguage, EnglishLanguage, ChineseLanguage)}, OptionHashType: Option{"", "--type", DefaultHashType, OptionTypeAlternative, fmt.Sprintf("%s/%s", DefaultHashType, MD5HashType), "", fmt.Sprintf("计算的类型, 默认值:%s, 取值范围: %s/%s", DefaultHashType, DefaultHashType, MD5HashType), fmt.Sprintf("hash type, Default: %s, value range is: %s/%s", DefaultHashType, DefaultHashType, MD5HashType)}, OptionVersion: Option{"-v", "--version", "", OptionTypeFlagTrue, "", "", fmt.Sprintf("显示ossutil的版本(%s)并退出。", Version), fmt.Sprintf("Show ossutil version (%s) and exit.", Version)}, OptionRequestPayer: Option{"", "--payer", "", OptionTypeString, "", "", "请求的支付方式,如果为请求者付费模式,可以将该值设置成\"requester\"", "The payer of the request. You can set this value to \"requester\" if you want pay for requester"}, OptionLogLevel: Option{"", "--loglevel", "", OptionTypeString, "", "", "日志级别,默认为空,表示不输出日志文件,可选值为:info|debug,info输出提示信息日志,debug输出详细信息日志(包括http请求和响应信息)", "log level,default is empty(no log file output),optional value is:info|debug,info will output information logs,debug will output detail logs(including http request and response logs)"}, OptionMaxUpSpeed: Option{"", "--maxupspeed", "", OptionTypeInt64, "", "", "最大上传速度,单位:KB/s,缺省值为0(不受限制)", "max upload speed,the unit is:KB/s,default value is 0(unlimited)"}, OptionUpload: Option{"", "--upload", "", OptionTypeFlagTrue, "", "", "表示上传到oss,主要在命令probe中使用", "specifies upload action to oss,primarily used in probe command"}, OptionDownload: Option{"", "--download", "", OptionTypeFlagTrue, "", "", "表示从oss下载,主要在命令probe中使用", "specifies download action from oss,primarily used in probe command"}, OptionUrl: Option{"", "--url", "", OptionTypeString, "", "", "表示一个url地址,主要在命令probe中使用", "specifies a url address,primarily used in probe command"}, OptionBucketName: Option{"", "--bucketname", "", OptionTypeString, "", "", "表示bucket的名称,主要在命令probe中使用", "specifies a name of bucket,primarily used in probe command"}, OptionObject: Option{"", "--object", "", OptionTypeString, "", "", "表示oss中对象的名称,主要在命令probe中使用", "specifies a name of object,primarily used in probe command"}, OptionAddr: Option{"", "--addr", "", OptionTypeString, "", "", "表示一个网络地址,通常为域名,主要在命令probe中使用", "specifies a network address,usually a domain,primarily used in probe command"}, OptionUpMode: Option{"", "--upmode", "", OptionTypeString, "", "", "表示上传模式,缺省值为normal,取值为:normal|append|multipart,分别表示正常上传、追加上传、分块上传,主要在命令probe中使用", "specifies the upload mode,default value is normal,optional value is:normal|append|multipart, which means normal upload、append upload and multipart upload,it is primarily used in probe command."}, OptionDisableEmptyReferer: Option{"", "--disable-empty-referer", "", OptionTypeFlagTrue, "", "", "表示不允许referer字段为空,主要在referer命令中使用", "specifies that the referer field is not allowed to be empty,primarily used in referer command"}, OptionMethod: Option{"", "--method", "", OptionTypeString, "", "", "表示命令的操作类型,取值为PUT、GET、DELETE、LIST等", "specifies the command's operation type. the values ​​are PUT, GET, DELETE, LIST, etc"}, OptionOrigin: Option{"", "--origin", "", OptionTypeString, "", "", "表示http请求头origin字段的值", "specifies the value of origin field in http header"}, OptionPartitionDownload: Option{"", "--partition-download", "", OptionTypeString, "", "", "分区下载使用,一个ossutil命令下载一个分区,其值格式为\"分区编号:总分区数\",比如1:5,表示当前ossutil下载分区1,总共有5个分区;分区号从1开始编号,objects的分区规则由工具内部算法决定;利用该选项,待下载的objects分成多个区,可以由多个ossutil命令一起下载完成,每个ossutil命令下载各自的分区,多个ossutil命令可以并行在不同机器上执行", "the option is used in partition download mode, one command to download one partition,the value format is \"partition number:total count of partitions\",such as 1:5, indicating that the command downloads partition 1,total partition count is 5; the partition number is numbered from 1, and the partitioning rules for objects are determined by ossutil; with this option, the objects to be downloaded are divided into multiple partitions, which can be downloaded by multiple ossutil commands,each ossutil command can download its own partition,multiple ossutil commands can be executed on different machines in parallel."}, OptionSSEAlgorithm: Option{"", "--sse-algorithm", "", OptionTypeString, "", "", "表示服务端加密算法,取值为KMS或者AES256", "specifies the server side encryption algorithm,value is KMS or AES256."}, OptionKMSMasterKeyID: Option{"", "--kms-masterkey-id", "", OptionTypeString, "", "", "表示kms秘钥托管服务中的主秘钥id", "specifies the primary key id in the kms(key management service)"}, OptionKMSDataEncryption: Option{"", "--kms-data-encryption", "", OptionTypeString, "", "", "表示kms秘钥托管服务使用的加密算法,目前取值仅支持为SM4, 或者为空", "specifies the kms data service encryption algorithm,Currently only supports the value SM4 or emtpy"}, OptionAcrHeaders: Option{"", "--acr-headers", "", OptionTypeString, "", "", "表示http header Access-Control-Request-Headers的值,主要用于cors-options命令", "specifies the value of the http header Access-Control-Request-Headers, primarily used in cors-options command."}, OptionAcrMethod: Option{"", "--acr-method", "", OptionTypeString, "", "", "表示http header Access-Control-Request-Method的值,主要用于cors-options命令", "specifies the value of the http header Access-Control-Request-Method,primarily used in cors-options command."}, OptionVersionId: Option{"", "--version-id", "", OptionTypeString, "", "", "表示object的版本id", "specifies the object's version id"}, OptionAllversions: Option{"", "--all-versions", "", OptionTypeFlagTrue, "", "", "表示object所有版本", "specifies the object's all versions"}, OptionVersionIdMarker: Option{"", "--version-id-marker", "", OptionTypeString, "", "", "表示列举objects所有版本的version id marker", "specifies the marker of object version id when list objects's all versions"}, OptionTrafficLimit: Option{"", "--trafic-limit", "", OptionTypeInt64, "", "", "http请求限速,单位:bit/s,缺省值为0(不受限制),用于sign命令", "http request speed limit,the unit is:bit/s,default value is 0(unlimited),primarily used in sign command"}, OptionProxyHost: Option{"", "--proxy-host", "", OptionTypeString, "", "", "网络代理服务器的url地址,支持http/https/socks5,比如 https://120.79.128.211:3128, socks5://120.79.128.211:1080", "url of network proxy server, which supports http/https/socks5, such as https://120.79.128.211:3128, socks5://120.79.128.211:1080"}, OptionProxyUser: Option{"", "--proxy-user", "", OptionTypeString, "", "", "网络代理服务器的用户名,默认为空", "username of network proxy, default is empty"}, OptionProxyPwd: Option{"", "--proxy-pwd", "", OptionTypeString, "", "", "网络代理服务器的密码,默认为空", "password of network proxy, default is empty"}, OptionLocalHost: Option{"", "--local-host", "", OptionTypeString, "", "", "工具的ip地址,比如 127.0.0.1", "ossutil's ip ,such as 127.0.0.1"}, OptionEnableSymlinkDir: Option{"", "--enable-symlink-dir", "", OptionTypeFlagTrue, "", "", "表示允许上传链接子目录下的文件,默认不上传; probe命令可以探测是否存在死循环链接文件或者目录", "specifies uploading link subdirectories,default are not uploaded; The probe command can detect whether there is a dead cycle symlink file or directory."}, OptionOnlyCurrentDir: Option{"", "--only-current-dir", "", OptionTypeFlagTrue, "", "", "表示仅操作当前目录下的文件或者object, 忽略子目录", "specifies that only files or objects in the current directory are manipulated, and subdirectories are ignored."}, OptionProbeItem: Option{"", "--probe-item", "", OptionTypeString, "", "", "表示probe命令的探测项目, 取值可为upload-speed, download-speed, cycle-symlink", "specifies probe command's probe item, the value can be upload-speed, download-speed, cycle-symlink"}, OptionDisableEncodeSlash: Option{"", "--disable-encode-slash", "", OptionTypeFlagTrue, "", "", "表示不对url path中的'/'进行编码, 主要用于sign命令", "specifies no encoding of '/' in url path section, primarily used in sign command"}, OptionDisableDirObject: Option{"", "--disable-dir-object", "", OptionTypeFlagTrue, "", "", "表示上传文件时不为目录生成oss对象,主要用于cp命令", "specifies that oss object is not generated for directory itself when uploading, primarily used in cp command"}, OptionRedundancyType: Option{"", "--redundancy-type", "", OptionTypeString, "", "", "表示bucket的数据容灾类型, 取值可为LRS, ZRS. LRS为默认值,表示本地容灾, ZRS表示更高可用的同城多可用区容灾(3AZ)", "specifies bucket data redundancy type, the value can be LRS, ZRS. LRS is default value, specifies locally redundant storage; ZRS specifies higher availability of redundant storage"}, OptionDisableAllSymlink: Option{"", "--disable-all-symlink", "", OptionTypeFlagTrue, "", "", "表示不允许上传目录下的链接文件以及链接目录, 缺省值为false", "specifies that uploading of symlink files and symlink directories under the directory is not allowed, the default value is false."}, OptionDisableIgnoreError: Option{"", "--disable-ignore-error", "", OptionTypeFlagTrue, "", "", "批量操作时候不忽略错误, 缺省值为false", "specifies that do not ignore errors during batch cp, default value is false"}, OptionTagging: Option{"", "--tagging", "", OptionTypeString, "", "", "设置object的tagging,取值格式如[\"TagA=A&TagB=B...\"]", "Set object tagging, value format is [\"TagA=A&TagB=B...]\""}, OptionStartTime: Option{"", "--start-time", "", OptionTypeInt64, "", "", "起始时间,为linux/Unix系统里面的时间戳,既从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数", "The start time is the timestamp in the Linux/Unix system, that is, the number of seconds that have passed since January 1, 1970 (midnight UTC/GMT)"}, OptionEndTime: Option{"", "--end-time", "", OptionTypeInt64, "", "", "结束时间,为linux/Unix系统里面的时间戳,既从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数", "The end time is the timestamp in the Linux/Unix system, that is, the number of seconds that have passed since January 1, 1970 (midnight UTC/GMT)"}, } func (T *Option) getHelp(language string) string { switch strings.ToLower(language) { case LEnglishLanguage: return T.helpEnglish default: return T.helpChinese } } // OptionMapType is the type for ossutil got options type OptionMapType map[string]interface{} // ParseArgOptions parse command line and returns args and options func ParseArgOptions() ([]string, OptionMapType, error) { options := initOption() goopt.Args = make([]string, 0, 4) goopt.Description = func() string { return "Simple tool for access OSS." } goopt.Parse(nil) if err := checkOption(options); err != nil { return nil, nil, err } return goopt.Args, options, nil } func initOption() OptionMapType { m := make(OptionMapType, len(OptionMap)) for name, option := range OptionMap { switch option.optionType { case OptionTypeInt64: val, _ := stringOption(option) m[name] = val case OptionTypeFlagTrue: val, _ := flagTrueOption(option) m[name] = val case OptionTypeAlternative: val, _ := stringOption(option) m[name] = val default: val, _ := stringOption(option) m[name] = val } } return m } func stringOption(option Option) (*string, error) { names, err := makeNames(option) if err == nil { // ignore option.def, set it to "", will assemble it after return goopt.String(names, "", option.getHelp(DefaultLanguage)), nil } return nil, err } func flagTrueOption(option Option) (*bool, error) { names, err := makeNames(option) if err == nil { return goopt.Flag(names, []string{}, option.getHelp(DefaultLanguage), ""), nil } return nil, err } func makeNames(option Option) ([]string, error) { if option.name == "" && option.nameAlias == "" { return nil, errors.New("Internal Error, invalid option whose name and nameAlias empty!") } var names []string if option.name == "" || option.nameAlias == "" { names = make([]string, 1) if option.name == "" { names[0] = option.nameAlias } else { names[0] = option.name } } else { names = make([]string, 2) names[0] = option.name names[1] = option.nameAlias } return names, nil } func checkOption(options OptionMapType) error { for name, optionInfo := range OptionMap { if option, ok := options[name]; ok { if optionInfo.optionType == OptionTypeInt64 { if val, ook := option.(*string); ook && *val != "" { num, err := strconv.ParseInt(*val, 10, 64) if err != nil { return fmt.Errorf("invalid option value of %s, the value: %s is not int64, please check", name, *val) } if optionInfo.minVal != "" { minv, _ := strconv.ParseInt(optionInfo.minVal, 10, 64) if num < minv { return fmt.Errorf("invalid option value of %s, the value: %d is smaller than the min value range: %d", name, num, minv) } } if optionInfo.maxVal != "" { maxv, _ := strconv.ParseInt(optionInfo.maxVal, 10, 64) if num > maxv { return fmt.Errorf("invalid option value of %s, the value: %d is bigger than the max value range: %d", name, num, maxv) } } } } if optionInfo.optionType == OptionTypeAlternative { if val, ook := option.(*string); ook && *val != "" { vals := strings.Split(optionInfo.minVal, "/") if FindPosCaseInsen(*val, vals) == -1 { return fmt.Errorf("invalid option value of %s, the value: %s is not anyone of %s", name, *val, optionInfo.minVal) } } } } } return nil } // GetBool is used to get bool option from option map parsed by ParseArgOptions func GetBool(name string, options OptionMapType) (bool, error) { if option, ok := options[name]; ok { if val, ook := option.(*bool); ook { return *val, nil } return false, fmt.Errorf("Error: option value of %s is not bool", name) } return false, fmt.Errorf("Error: there is no option for %s", name) } // GetInt is used to get int option from option map parsed by ParseArgOptions func GetInt(name string, options OptionMapType) (int64, error) { if option, ok := options[name]; ok { switch option.(type) { case *string: val, err := strconv.ParseInt(*(option.(*string)), 10, 64) if err == nil { return val, nil } if *(option.(*string)) == "" { return 0, fmt.Errorf("Option value of %s is empty", name) } return 0, err case *int64: return *(option.(*int64)), nil default: return 0, fmt.Errorf("Option value of %s is not int64", name) } } else { return 0, fmt.Errorf("There is no option for %s", name) } } // GetString is used to get string option from option map parsed by ParseArgOptions func GetString(name string, options OptionMapType) (string, error) { if option, ok := options[name]; ok { if val, ook := option.(*string); ook { return *val, nil } return "", fmt.Errorf("Error: Option value of %s is not string", name) } return "", fmt.Errorf("Error: There is no option for %s", name) }
StreamFrequency.enum.ts
export enum STREAM_FREQUENCY { SECOND = 1,
MINUTE, DAILY, WEEKELY, MONTHLY, }