|
| 1 | +/*! |
| 2 | + * Copyright 2020 Google Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import { HttpRequestConfig, HttpClient, HttpError, AuthorizedHttpClient } from '../utils/api-request'; |
| 18 | +import { PrefixedFirebaseError } from '../utils/error'; |
| 19 | +import { FirebaseMachineLearningError, MachineLearningErrorCode } from './machine-learning-utils'; |
| 20 | +import * as utils from '../utils/index'; |
| 21 | +import * as validator from '../utils/validator'; |
| 22 | +import { FirebaseApp } from '../firebase-app'; |
| 23 | + |
| 24 | +const ML_V1BETA1_API = 'https://mlkit.googleapis.com/v1beta1'; |
| 25 | +const FIREBASE_VERSION_HEADER = { |
| 26 | + 'X-Firebase-Client': 'fire-admin-node/<XXX_SDK_VERSION_XXX>', |
| 27 | +}; |
| 28 | + |
| 29 | +export interface StatusErrorResponse { |
| 30 | + readonly code: number; |
| 31 | + readonly message: string; |
| 32 | +} |
| 33 | + |
| 34 | +export interface ModelContent { |
| 35 | + readonly displayName?: string; |
| 36 | + readonly tags?: string[]; |
| 37 | + readonly state?: { |
| 38 | + readonly validationError?: StatusErrorResponse; |
| 39 | + readonly published?: boolean; |
| 40 | + }; |
| 41 | + readonly tfliteModel?: { |
| 42 | + readonly gcsTfliteUri: string; |
| 43 | + readonly sizeBytes: number; |
| 44 | + }; |
| 45 | +} |
| 46 | + |
| 47 | +export interface ModelResponse extends ModelContent { |
| 48 | + readonly name: string; |
| 49 | + readonly createTime: string; |
| 50 | + readonly updateTime: string; |
| 51 | + readonly etag: string; |
| 52 | + readonly modelHash?: string; |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +/** |
| 57 | + * Class that facilitates sending requests to the Firebase ML backend API. |
| 58 | + * |
| 59 | + * @private |
| 60 | + */ |
| 61 | +export class MachineLearningApiClient { |
| 62 | + private readonly httpClient: HttpClient; |
| 63 | + private projectIdPrefix?: string; |
| 64 | + |
| 65 | + constructor(private readonly app: FirebaseApp) { |
| 66 | + if (!validator.isNonNullObject(app) || !('options' in app)) { |
| 67 | + throw new FirebaseMachineLearningError( |
| 68 | + 'invalid-argument', |
| 69 | + 'First argument passed to admin.machineLearning() must be a valid ' |
| 70 | + + 'Firebase app instance.'); |
| 71 | + } |
| 72 | + |
| 73 | + this.httpClient = new AuthorizedHttpClient(app); |
| 74 | + } |
| 75 | + |
| 76 | + public getModel(modelId: string): Promise<ModelResponse> { |
| 77 | + return Promise.resolve() |
| 78 | + .then(() => { |
| 79 | + return this.getModelName(modelId); |
| 80 | + }) |
| 81 | + .then((modelName) => { |
| 82 | + return this.getResource<ModelResponse>(modelName); |
| 83 | + }); |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * Gets the specified resource from the ML API. Resource names must be the short names without project |
| 88 | + * ID prefix (e.g. `models/123456789`). |
| 89 | + * |
| 90 | + * @param {string} name Full qualified name of the resource to get. |
| 91 | + * @returns {Promise<T>} A promise that fulfills with the resource. |
| 92 | + */ |
| 93 | + private getResource<T>(name: string): Promise<T> { |
| 94 | + return this.getUrl() |
| 95 | + .then((url) => { |
| 96 | + const request: HttpRequestConfig = { |
| 97 | + method: 'GET', |
| 98 | + url: `${url}/${name}`, |
| 99 | + }; |
| 100 | + return this.sendRequest<T>(request); |
| 101 | + }); |
| 102 | + } |
| 103 | + |
| 104 | + private sendRequest<T>(request: HttpRequestConfig): Promise<T> { |
| 105 | + request.headers = FIREBASE_VERSION_HEADER; |
| 106 | + return this.httpClient.send(request) |
| 107 | + .then((resp) => { |
| 108 | + return resp.data as T; |
| 109 | + }) |
| 110 | + .catch((err) => { |
| 111 | + throw this.toFirebaseError(err); |
| 112 | + }); |
| 113 | + } |
| 114 | + |
| 115 | + private toFirebaseError(err: HttpError): PrefixedFirebaseError { |
| 116 | + if (err instanceof PrefixedFirebaseError) { |
| 117 | + return err; |
| 118 | + } |
| 119 | + |
| 120 | + const response = err.response; |
| 121 | + if (!response.isJson()) { |
| 122 | + return new FirebaseMachineLearningError( |
| 123 | + 'unknown-error', |
| 124 | + `Unexpected response with status: ${response.status} and body: ${response.text}`); |
| 125 | + } |
| 126 | + |
| 127 | + const error: Error = (response.data as ErrorResponse).error || {}; |
| 128 | + let code: MachineLearningErrorCode = 'unknown-error'; |
| 129 | + if (error.status && error.status in ERROR_CODE_MAPPING) { |
| 130 | + code = ERROR_CODE_MAPPING[error.status]; |
| 131 | + } |
| 132 | + const message = error.message || `Unknown server error: ${response.text}`; |
| 133 | + return new FirebaseMachineLearningError(code, message); |
| 134 | + } |
| 135 | + |
| 136 | + private getUrl(): Promise<string> { |
| 137 | + return this.getProjectIdPrefix() |
| 138 | + .then((projectIdPrefix) => { |
| 139 | + return `${ML_V1BETA1_API}/${this.projectIdPrefix}`; |
| 140 | + }); |
| 141 | + } |
| 142 | + |
| 143 | + private getProjectIdPrefix(): Promise<string> { |
| 144 | + if (this.projectIdPrefix) { |
| 145 | + return Promise.resolve(this.projectIdPrefix); |
| 146 | + } |
| 147 | + |
| 148 | + return utils.findProjectId(this.app) |
| 149 | + .then((projectId) => { |
| 150 | + if (!validator.isNonEmptyString(projectId)) { |
| 151 | + throw new FirebaseMachineLearningError( |
| 152 | + 'invalid-argument', |
| 153 | + 'Failed to determine project ID. Initialize the SDK with service account credentials, or ' |
| 154 | + + 'set project ID as an app option. Alternatively, set the GOOGLE_CLOUD_PROJECT ' |
| 155 | + + 'environment variable.'); |
| 156 | + } |
| 157 | + |
| 158 | + this.projectIdPrefix = `projects/${projectId}`; |
| 159 | + return this.projectIdPrefix; |
| 160 | + }); |
| 161 | + } |
| 162 | + |
| 163 | + private getModelName(modelId: string): string { |
| 164 | + if (!validator.isNonEmptyString(modelId)) { |
| 165 | + throw new FirebaseMachineLearningError( |
| 166 | + 'invalid-argument', 'Model ID must be a non-empty string.'); |
| 167 | + } |
| 168 | + |
| 169 | + if (modelId.indexOf('/') !== -1) { |
| 170 | + throw new FirebaseMachineLearningError( |
| 171 | + 'invalid-argument', 'Model ID must not contain any "/" characters.'); |
| 172 | + } |
| 173 | + |
| 174 | + return `models/${modelId}`; |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +interface ErrorResponse { |
| 179 | + error?: Error; |
| 180 | +} |
| 181 | + |
| 182 | +interface Error { |
| 183 | + code?: number; |
| 184 | + message?: string; |
| 185 | + status?: string; |
| 186 | +} |
| 187 | + |
| 188 | +const ERROR_CODE_MAPPING: {[key: string]: MachineLearningErrorCode} = { |
| 189 | + INVALID_ARGUMENT: 'invalid-argument', |
| 190 | + NOT_FOUND: 'not-found', |
| 191 | + RESOURCE_EXHAUSTED: 'resource-exhausted', |
| 192 | + UNAUTHENTICATED: 'authentication-error', |
| 193 | + UNKNOWN: 'unknown-error', |
| 194 | +}; |
0 commit comments