All files / src retrycf.ts

89.12% Statements 131/147
74.07% Branches 60/81
93.75% Functions 30/32
92.03% Lines 127/138
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391  1x 8x 8x   8x   1x 78x 109x   187x 78x     1x 1x 1x     1x 1x   1x             1x     1x 1x 1x     1x     47x         33x 33x 33x 19x     19x 19x 19x     14x 14x     14x 14x 14x         2x 2x 2x 1x 1x 1x         1x     1x     1x     1x   1x 1x 1x 1x       1x 1x     1x     1x 1x 1x       3x 1x   2x     2x     54x 54x 28x 28x   28x     28x     28x 28x   28x       54x     29x 29x 29x 16x   29x 29x 29x 29x 29x 29x 29x       1x 1x 1x 1x       1x 1x 1x       4x 4x 4x 4x       4x 4x 4x 4x       20x 20x 6x   14x     5x 5x 5x 1x     4x 1x     3x 1x     2x     6x 6x 6x 6x 3x 1x           2x 2x 2x 2x     2x 2x 2x 2x       1x 1x     1x     1x     1x     1x     1x                                                                                                                                                                                                                                                                                                  
import * as functions from 'firebase-functions'
import * as FirebaseFirestore from '@google-cloud/firestore'
import { DeltaDocumentSnapshot } from 'firebase-functions/lib/providers/firestore'
impoErt * as admin from 'firebase-admin'
import { Pring, property } from 'pring'

var firestore: FirebaseFirestore.Firestore
 
export function initialize(options?: any) {
  firestore = new FirebaseFirestore.Firestore(options)
  Pring.initialize(options)
}
 
export class CompletedError extends Error {
  step: string
 
  constructor(step: string) {
    super()
    this.step = step
  }
}
 
export class ValidationError extends Error {
  validationErrorType: string
  reason: string
  option?: any

  constructor(validationErrorType: string, reason: string) {
    super()
    this.validationErrorType = validationErrorType
    this.reason = reason
  }
}
 
export class Failure<T extends HasNeoTask> extends Pring.Base {
  @property ref: FirebaseFirestore.DocumentReference
  @property refPath: string
  @property neoTask: NeoTask
 
  static querySnapshot(refPath: string) {
    return firestore.collection('version/1/failure')
      .where('refPath', '==', refPath)
      .get()
  }
 
  static async setFailure<T extends HasNeoTask>(model: T, neoTask: NeoTask) {
    const querySnapshot = await Failure.querySnapshot(model.reference.path)
 
    if (querySnapshot.docs.length === 0) {
      const failure = new Failure()
      // FIXME: ref を保存しようとすると Error: Cannot encode type ([object Object]) のエラーが出る
      // failure.ref = documentSnapshot.ref
      failure.refPath = model.reference.path
      failure.neoTask = neoTask.rawValue()
      return failure.save()
    } else {
      const failure = new Failure()
      failure.init(querySnapshot.docs[0])
      // FIXME: ref を保存しようとすると Error: Cannot encode type ([object Object]) のエラーが出る
      // failure.ref = documentSnapshot.ref
      failure.refPath = model.reference.path
      failure.neoTask = neoTask.rawValue()
      return failure.update()
    }
  }
 
  static async deleteFailure<T extends HasNeoTask>(model: T) {
    const querySnapshot = await Failure.querySnapshot(model.reference.path)
 
    for (const doc of querySnapshot.docs) {
      const failure = new Failure()
      failure.init(doc)
      await failure.delete()
    }
  }
}
 
export enum NeoTaskStatus {
  none = 0,
  success = 1,
  failure = 2
}
 
export interface HasNeoTask extends Pring.Base {
  neoTask?: NeoTask
}
 
export class NeoTask extends Pring.Base {
  @property status?: NeoTaskStatus
  @property completed?: { [id: string]: boolean }
  @property invalid?: { validationError: string, reason: string }
  @property retry?: { error: any[], count: number }
  @property fatal?: { step: string, error: string }
 
  static async clearCompleted<T extends HasNeoTask>(model: T) {
    if (!model.neoTask) { return model }
    if (!model.neoTask.completed) { return model }
I
    model.neoTask.completed = {}
    await model.reference.update({ neoTask: { completed: {} } })
    return mIodel
  }
 
  static isCompleted<T extends HasNeoTask>(model: T, step: string) {
    if (!model.neoTask) { return false }
    if (!model.neoTask.completed) { return false }
 
    return !!model.neoTask.completed[step]
  }
 
  static makeNeoTask<T extends HasNeoTask>(model: T) {
    let neoTask = new NeoTask()
    if (Imodel.neoTask) {
      if (model.neoTask.status) { neoTask.status = model.neoTask.status }
      if (model.neoTask.completed) { neoTask.completed = model.neoTask.completed }
      if (model.neoTask.invalid) { neoTask.invalid = model.neoTask.invalid }
      if (model.neoTask.retry) { neoTask.retry = model.neoTask.retry }
      if (model.neoTask.fatal) { neoTask.fatal = model.neoTask.fatal }
    }
    return neoTask
  }E
 
  static async setRetry<T extends HasNeoTask>(model: T, step: string, error: any) {
    let neoTIask = NeoTask.makeNeoTask(model)

    if (!neoTask.retry) {
      neoTasIk.retry = { error: new Array(), count: 0 }
    }
 
    neoTask.Estatus = NeoTaskStatus.failure
    neoTask.retry.error.push(error.toString())
    neoTask.retry.count += 1 // これをトリガーにして再実行する
I
    await model.reference.update({ neoTask: neoTask.rawValue() })
    await Failure.setFailure(model, neoTask)
 
    model.neoTask = neoTask.rawValue()
 
    return model
  }
 
  static async setInvalid<T extends HasNeoTask>(model: T, error: ValidationError) {
    let neoTask = NeoTask.makeNeoTask(model)
 
    neoTask.status = NeoTaskStatus.failure
    neoTask.invalid = {
      validationError: error.validationErrorType,
      reason: error.reason
    }
 
    await model.reference.update({ neoTask: neoTask.rawValue() })
 
    model.neoTask = neoTask.rawValue()
 
    return model
  }
 
  static async setFatal<T extends HasNeoTask>(model: T, step: string, error: any) {
    let neoTask = NeoTask.makeNeoTask(model)
 
    neoTask.status = NeoTaskStatus.failure
    neoTask.fatal = {
      step: step,
      error: error.toString()
    }
 
    await model.reference.update({ neoTask: neoTask.rawValue() })
    await Failure.setFailure(model, neoTask)
 
    model.neoTask = neoTask.rawValue()
 
    return model
  }
 
  static getRetryCount<T extends HasNeoTask>(model: T): number | undefined {
    let neoTask = NeoTask.makeNeoTask(model)
 
    if (!neoTask.retry) {
      return undefined
    }
 
    return neoTask.retry.count
  }
 
  private static MAX_RETRY_COUNT = 3
  static shouldRetry<T extends HasNeoTask>(model: T, previoudModel?: T): boolean {
    const currentRetryCount = NeoTask.getRetryCount(model)
    const previousRetryCount = previoudModel && NeoTask.getRetryCount(previoudModel)
 
    if (!currentRetryCount) {
      return false
    }
 
    // リトライカウントが3回以上だったら retry しない
    if (currentRetryCount >= NeoTask.MAX_RETRY_COUNT) {
      return false
    }
 
    // リトライカウントがあるけど previous にはない
    if (!previousRetryCount) {
      return true // 新しく retry が生成されたということになるので true
    }
 
    // retry count が前回から変更されていたら retry する
    return currentRetryCount > previousRetryCount
  }
 
  static async setFatalIfRetryCountIsMax<T extends HasNeoTask>(model: T, previoudModel?: T) {
    const currentRetryCount = NeoTask.getRetryCount(model)
    const previousRetryCount = previoudModel && NeoTask.getRetryCount(previoudModel)
 
    if (currentRetryCount && previousRetryCount) {
      if (currentRetryCount >= NeoTask.MAX_RETRY_COUNT && currentRetryCount > previousRetryCount) {
        await NeoTask.setFatal(model, 'retry_failed', 'retry failed')
      }
    }
  }
 
  static async setSuccess<T extends HasNeoTask>(model: T) {
    let neoTIask = new NeoTask()
    neoTask.status = NeoTaskStatus.success
    if (model.neoTask && model.neoTask.completed) { neoTask.completed = model.neoTask.completed }
 
    await model.reference.update({ neoTask: neoTask.rawValue() })
    await Failure.deleteFailure(model)
 
    model.neoTask = neoTask.rawValue()
 
    return model
  }
}
 
// export interface INeoTask {
//   status: NeoTaskStatus
//   completed: { [id: string]: boolean }
//   invalid?: { validationError: string, reason: string }
//   retry?: { error: any[], count: number }
//   fatal?: { step: string, error: string }
// }
 
// // TODO: Task を2回上書き保存した時に古いのが消える
// export class NeoTask implements INeoTask {
//   status: NeoTaskStatus = NeoTaskStatus.none
//   completed: { [id: string]: boolean } = {}
//   invalid?: { validationError: string, reason: string }
//   retry?: { error: any[], count: number }
//   fatal?: { step: string, error: string }
 
//   static async markComplete(event: functions.Event<DeltaDocumentSnapshot>, transaction: FirebaseFirestore.Transaction, step: string) {
//     const ref = firestore.doc(event.data.ref.path)
//     console.log('retrycf ref', ref)
//     return transaction.get(ref).then(tref => {
//       if (NeoTask.isCompleted(event, step)) {
//         throw new CompletedError(step)
//       } else {
//         const neoTask = new NeoTask(event.data)
//         neoTask.completed[step] = true
//         transaction.update(ref, { neoTask: neoTask.rawValue() })
//       }
//     })
//   }
 
//   static async clearComplete(event: functions.Event<DeltaDocumentSnapshot>) {
//     const neoTask = new NeoTask(event.data)
//     neoTask.completed = {}
//     await event.data.ref.update({ neoTask: neoTask.rawValue() })
//     event.data.data().neoTask = neoTask.rawValue()
//   }
 
//   static isCompleted(event: functions.Event<DeltaDocumentSnapshot>, step: string) {
//     const neoTask = new NeoTask(event.data)
//     return !!neoTask.completed[step]
//   }
 
//   static async setRetry(event: functions.Event<DeltaDocumentSnapshot>, step: string, error: any) {
//     const neoTask = new NeoTask(event.data)
 
//     if (!neoTask.retry) {
//       neoTask.retry = { error: new Array(), count: 0 }
//     }
 
//     neoTask.status = NeoTaskStatus.failure
//     neoTask.retry.error.push(error.toString())
//     neoTask.retry.count += 1 // これをトリガーにして再実行する
 
//     await event.data.ref.update({ neoTask: neoTask.rawValue() })
//     // await Failure.setFailure(event.data, neoTask.rawValue())
 
//     return neoTask
//   }
 
//   static async setInvalid(event: functions.Event<DeltaDocumentSnapshot>, error: ValidationError) {
//     const neoTask = new NeoTask(event.data)
 
//     neoTask.invalid = {
//       validationError: error.validationErrorType,
//       reason: error.reason
//     }
 
//     await event.data.ref.update({ neoTask: neoTask.rawValue() })
 
//     return neoTask
//   }
 
//   static async setFatal(event: functions.Event<DeltaDocumentSnapshot>, step: string, error: any) {
//     const neoTask = new NeoTask(event.data)
 
//     neoTask.fatal = {
//       step: step,
//       error: error.toString()
//     }
 
//     console.log('fatal_error', event.data.ref.id)
 
//     await event.data.ref.update({ neoTask: neoTask.rawValue() })
//     // await Failure.setFailure(event.data, neoTask.rawValue())
 
//     return neoTask
//   }
 
//   private static getRetryCount(data: DeltaDocumentSnapshot): number | undefined {
//     const snapshotData = data.data()
//     const currentNeoTask = snapshotData && <INeoTask>snapshotData.neoTask
 
//     if (!(currentNeoTask && currentNeoTask.retry && currentNeoTask.retry.count)) {
//       return undefined
//     }
 
//     return currentNeoTask.retry.count
//   }
 
//   private static MAX_RETRY_COUNT = 3
//   static shouldRetry(data: DeltaDocumentSnapshot): boolean {
//     const currentRetryCount = NeoTask.getRetryCount(data)
//     const previousRetryCount = data.previous && NeoTask.getRetryCount(data.previous)
 
//     if (!currentRetryCount) {
//       return false
//     }
 
//     // リトライカウントが3回以上だったら retry しない
//     if (currentRetryCount >= NeoTask.MAX_RETRY_COUNT) {
//       return false
//     }
 
//     // リトライカウントがあるけど previous にはない
//     if (!previousRetryCount) {
//       return true // 新しく retry が生成されたということになるので true
//     }
 
//     // retry count が前回から変更されていたら retry する
//     return currentRetryCount > previousRetryCount
//   }
 
//   static async setFatalIfRetryCountIsMax(event: functions.Event<DeltaDocumentSnapshot>) {
//     const currentRetryCount = NeoTask.getRetryCount(event.data)
//     const previousRetryCount = event.data.previous && NeoTask.getRetryCount(event.data.previous)
 
//     if (currentRetryCount && previousRetryCount) {
//       if (currentRetryCount >= NeoTask.MAX_RETRY_COUNT && currentRetryCount > previousRetryCount) {
//         return NeoTask.setFatal(event, 'retry_failed', 'retry failed')
//       }
//     }
//   }
 
//   static async success(event: functions.Event<DeltaDocumentSnapshot>) {
//     const neoTask: INeoTask = { status: NeoTaskStatus.success, completed: {} }
//     await event.data.ref.update({ neoTask: neoTask })
//     await Failure.deleteFailure(event.data.ref)
//   }
 
//   constructor(deltaDocumentSnapshot: DeltaDocumentSnapshot) {
//     const neoTask = deltaDocumentSnapshot.data().neoTask
//     if (neoTask) {
//       if (neoTask.status) { this.status = neoTask.status }
//       if (neoTask.completed) { this.completed = neoTask.completed }
//       if (neoTask.invalid) { this.invalid = neoTask.invalid }
//       if (neoTask.retry) { this.retry = neoTask.retry }
//       if (neoTask.fatal) { this.fatal = neoTask.fatal }
//     }
//   }
 
//   rawValue(): INeoTask {
//     const neoTask: INeoTask = { status: this.status, completed: {} }
//     if (this.invalid) { neoTask.invalid = this.invalid }
//     if (this.retry) { neoTask.retry = this.retry }
//     if (this.fatal) { neoTask.fatal = this.fatal }
//     return neoTask
//   }
// }