UNPKG

102 kBTypeScriptView Raw
1/**
2 * Faast.js transforms ordinary JavaScript modules into serverless cloud
3 * functions that can run on AWS Lambda and Google Cloud Functions.
4 *
5 * The main entry point to faast.js is the {@link faast} function, which returns
6 * an object that implements the {@link FaastModule} interface. The most common
7 * options are {@link CommonOptions}. Using faast.js requires writing two
8 * modules, one containing the functions to upload to the cloud, and the other
9 * that invokes faast.js and calls the resulting cloud functions.
10 * @packageDocumentation
11 */
12
13/// <reference types="node" />
14
15import * as childProcess from 'child_process';
16import { cloudbilling_v1 } from 'googleapis';
17import { cloudfunctions_v1 } from 'googleapis';
18import { CloudWatchLogs } from 'aws-sdk';
19import { ConfigurationOptions } from 'aws-sdk/lib/config-base';
20import * as debug_2 from 'debug';
21import { GoogleApis } from 'googleapis';
22import { IAM } from 'aws-sdk';
23import { Lambda } from 'aws-sdk';
24import { Pricing } from 'aws-sdk';
25import { pubsub_v1 } from 'googleapis';
26import { Readable } from 'stream';
27import { S3 } from 'aws-sdk';
28import { SNS } from 'aws-sdk';
29import { SQS } from 'aws-sdk';
30import { STS } from 'aws-sdk';
31import { VError } from 'verror';
32import * as webpack from 'webpack';
33import { Writable } from 'stream';
34
35declare type AnyFunction = (...args: any[]) => any;
36
37/**
38 * `Async<T>` maps regular values to Promises and Iterators to AsyncIterators,
39 * If `T` is already a Promise or an AsyncIterator, it remains the same. This
40 * type is used to infer the return value of cloud functions from the types of
41 * the functions in the user's input module.
42 * @public
43 */
44export declare type Async<T> = T extends AsyncGenerator<infer R> ? AsyncGenerator<R> : T extends Generator<infer R> ? AsyncGenerator<R> : T extends Promise<infer R> ? Promise<R> : Promise<T>;
45
46/**
47 * `AsyncDetail<T>` is similar to {@link Async} except it maps retun values R to
48 * `Detail<R>`, which is the return value with additional information about each
49 * cloud function invocation.
50 * @public
51 */
52export declare type AsyncDetail<T> = T extends AsyncGenerator<infer R> ? AsyncGenerator<Detail<R>> : T extends Generator<infer R> ? AsyncGenerator<Detail<R>> : T extends Promise<infer R> ? Promise<Detail<R>> : Promise<Detail<T>>;
53
54declare class AsyncIterableQueue<T> extends AsyncQueue<IteratorResult<T>> {
55 push(value: T | Promise<T>): void;
56 done(): void;
57 [Symbol.asyncIterator](): this;
58}
59
60declare class AsyncQueue<T> {
61 protected deferred: Array<Deferred<T>>;
62 protected enqueued: Promise<T>[];
63 enqueue(value: T | Promise<T>): void;
64 next(): Promise<T>;
65 clear(): void;
66}
67
68/**
69 * The return type of {@link faastAws}. See {@link FaastModuleProxy}.
70 * @public
71 */
72export declare type AwsFaastModule<M extends object = object> = FaastModuleProxy<M, AwsOptions, AwsState>;
73
74declare type AwsGcWork = {
75 type: "SetLogRetention";
76 logGroupName: string;
77 retentionInDays: number;
78} | {
79 type: "DeleteResources";
80 resources: AwsResources;
81} | {
82 type: "DeleteLayerVersion";
83 LayerName: string;
84 VersionNumber: number;
85};
86
87declare interface AwsLayerInfo {
88 Version: number;
89 LayerVersionArn: string;
90 LayerName: string;
91}
92
93declare class AwsMetrics {
94 outboundBytes: number;
95 sns64kRequests: number;
96 sqs64kRequests: number;
97}
98
99/**
100 * AWS-specific options for {@link faastAws}.
101 * @public
102 */
103export declare interface AwsOptions extends CommonOptions {
104 /**
105 * The region to create resources in. Garbage collection is also limited to
106 * this region. Default: `"us-west-2"`.
107 */
108 region?: AwsRegion;
109 /**
110 * The role that the lambda function will assume when executing user code.
111 * Default: `"faast-cached-lambda-role"`. Rarely used.
112 * @remarks
113 * When a lambda executes, it first assumes an
114 * {@link https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html | execution role}
115 * to grant access to resources.
116 *
117 * By default, faast.js creates this execution role for you and leaves it
118 * permanently in your account (the role is shared across all lambda
119 * functions created by faast.js). By default, faast.js grants administrator
120 * privileges to this role so your code can perform any AWS operation it
121 * requires.
122 *
123 * You can
124 * {@link https://console.aws.amazon.com/iam/home#/roles | create a custom role}
125 * that specifies more limited permissions if you prefer not to grant
126 * administrator privileges. Any role you assign for faast.js modules needs
127 * at least the following permissions:
128 *
129 * - Execution Role:
130 * ```json
131 * {
132 * "Version": "2012-10-17",
133 * "Statement": [
134 * {
135 * "Effect": "Allow",
136 * "Action": ["logs:*"],
137 * "Resource": "arn:aws:logs:*:*:log-group:faast-*"
138 * },
139 * {
140 * "Effect": "Allow",
141 * "Action": ["sqs:*"],
142 * "Resource": "arn:aws:sqs:*:*:faast-*"
143 * }
144 * ]
145 * }
146 * ```
147 *
148 * - Trust relationship (also known as `AssumeRolePolicyDocument` in the AWS
149 * SDK):
150 * ```json
151 * {
152 * "Version": "2012-10-17",
153 * "Statement": [
154 * {
155 * "Effect": "Allow",
156 * "Principal": {
157 * "Service": "lambda.amazonaws.com"
158 * },
159 * "Action": "sts:AssumeRole"
160 * }
161 * ]
162 * }
163 * ```
164 *
165 */
166 RoleName?: string;
167 /**
168 * Additional options to pass to AWS Lambda creation. See
169 * {@link https://docs.aws.amazon.com/lambda/latest/dg/API_CreateFunction.html | CreateFunction}.
170 * @remarks
171 * If you need specialized options, you can pass them to the AWS Lambda SDK
172 * directly. Note that if you override any settings set by faast.js, you may
173 * cause faast.js to not work:
174 *
175 * ```typescript
176 * const request: aws.Lambda.CreateFunctionRequest = {
177 * FunctionName,
178 * Role,
179 * Runtime: "nodejs14.x",
180 * Handler: "index.trampoline",
181 * Code,
182 * Description: "faast trampoline function",
183 * Timeout,
184 * MemorySize,
185 * ...awsLambdaOptions
186 * };
187 * ```
188 */
189 awsLambdaOptions?: Partial<Lambda.CreateFunctionRequest>;
190 /**
191 * Additional options to pass to all AWS services. See
192 * {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Config.html | AWS.Config}.
193 * @remarks
194 * If you need to specify AWS options such as credentials, you can pass set
195 * these options here. Note that faast.js will override some options even if
196 * they are specified here, specifically the options used to create the
197 * `Lambda` service, to ensure they allow for faast to function correctly.
198 * Options set in {@link CommonOptions} override those set here.
199 *
200 * Example of passing in credentials:
201 *
202 * ```typescript
203 * const credentials = { accessKeyId, secretAccessKey };
204 * const m = await faastAws(funcs, { credentials });
205 * ```
206 */
207 awsConfig?: ConfigurationOptions;
208 /** @internal */
209 _gcWorker?: (work: AwsGcWork, services: AwsServices) => Promise<void>;
210}
211
212/**
213 * Valid AWS
214 * {@link https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html | regions}.
215 * Not all of these regions have Lambda support.
216 * @public
217 */
218export declare type AwsRegion = "us-east-1" | "us-east-2" | "us-west-1" | "us-west-2" | "ca-central-1" | "eu-central-1" | "eu-west-1" | "eu-west-2" | "eu-west-3" | "ap-northeast-1" | "ap-northeast-2" | "ap-northeast-3" | "ap-southeast-1" | "ap-southeast-2" | "ap-south-1" | "sa-east-1";
219
220declare interface AwsResources {
221 FunctionName: string;
222 RoleName: string;
223 region: AwsRegion;
224 ResponseQueueUrl?: string;
225 ResponseQueueArn?: string;
226 RequestTopicArn?: string;
227 SNSLambdaSubscriptionArn?: string;
228 logGroupName: string;
229 layer?: AwsLayerInfo;
230 Bucket?: string;
231}
232
233declare interface AwsServices {
234 readonly lambda: Lambda;
235 readonly lambda2: Lambda;
236 readonly cloudwatch: CloudWatchLogs;
237 readonly iam: IAM;
238 readonly sqs: SQS;
239 readonly sns: SNS;
240 readonly pricing: Pricing;
241 readonly sts: STS;
242 readonly s3: S3;
243}
244
245/**
246 * @public
247 */
248declare interface AwsState {
249 /** @internal */
250 resources: AwsResources;
251 /** @internal */
252 services: AwsServices;
253 /** @internal */
254 options: Required<AwsOptions>;
255 /** @internal */
256 metrics: AwsMetrics;
257 /** @internal */
258 gcPromise?: Promise<"done" | "skipped">;
259}
260
261declare interface Blob_2 {
262}
263
264declare interface CallId {
265 callId: string;
266}
267
268declare type CallId_2 = string;
269
270declare interface CallingContext {
271 call: FunctionCall;
272 startTime: number;
273 logUrl?: string;
274 executionId?: string;
275 instanceId?: string;
276}
277
278/**
279 * Options that apply to the {@link FaastModule.cleanup} method.
280 * @public
281 */
282export declare interface CleanupOptions {
283 /**
284 * If true, delete provider cloud resources. Default: true.
285 * @remarks
286 * The cleanup operation has two functions: stopping the faast.js runtime
287 * and deleting cloud resources that were instantiated. If `deleteResources`
288 * is false, then only the runtime is stopped and no cloud resources are
289 * deleted. This can be useful for debugging and examining the state of
290 * resources created by faast.js.
291 *
292 * It is supported to call {@link FaastModule.cleanup} twice: once with
293 * `deleteResources` set to `false`, which only stops the runtime, and then
294 * again set to `true` to delete resources. This can be useful for testing.
295 */
296 deleteResources?: boolean;
297 /**
298 * If true, delete cached resources. Default: false.
299 * @remarks
300 * Some resources are cached persistently between calls for performance
301 * reasons. If this option is set to true, these cached resources are
302 * deleted when cleanup occurs, instead of being left behind for future use.
303 * For example, on AWS this includes the Lambda Layers that are created for
304 * {@link CommonOptions.packageJson} dependencies. Note that only the cached
305 * resources created by this instance of FaastModule are deleted, not cached
306 * resources from other FaastModules. This is similar to setting
307 * `useCachedDependencies` to `false` during function construction, except
308 * `deleteCaches` can be set at function cleanup time, and any other
309 * FaastModules created before cleanup may use the cached Layers.
310 */
311 deleteCaches?: boolean;
312 /**
313 * Number of seconds to wait for garbage collection. Default: 10.
314 * @remarks
315 * Garbage collection can still be operating when cleanup is called; this
316 * option limits the amount of time faast waits for the garbage collector.
317 * If set to 0, the wait is unlimited.
318 */
319 gcTimeout?: number;
320}
321
322/**
323 * Options common across all faast.js providers. Used as argument to {@link faast}.
324 * @remarks
325 * There are also more specific options for each provider. See
326 * {@link AwsOptions}, {@link GoogleOptions}, and {@link LocalOptions}.
327 * @public
328 */
329export declare interface CommonOptions {
330 /**
331 * If true, create a child process to isolate user code from faast
332 * scaffolding. Default: true.
333 * @remarks
334 * If a child process is not created, faast runs in the same node instance
335 * as the user code and may not execute in a timely fashion because user
336 * code may
337 * {@link https://nodejs.org/en/docs/guides/dont-block-the-event-loop/ | block the event loop}.
338 * Creating a child process for user code allows faast.js to continue
339 * executing even if user code never yields. This provides better
340 * reliability and functionality:
341 *
342 * - Detect timeout errors more reliably, even if the function doesn't
343 * relinquish the CPU. Not applicable to AWS, which sends separate failure
344 * messages in case of timeout. See {@link CommonOptions.timeout}.
345 *
346 * - CPU metrics used for detecting invocations with high latency, which can
347 * be used for automatically retrying calls to reduce tail latency.
348 *
349 * The cost of creating a child process is mainly in the memory overhead of
350 * creating another node process.
351 */
352 childProcess?: boolean;
353 /**
354 * When childProcess is true, the child process will be spawned with the
355 * value of this property as the setting for --max-old-space-size.
356 * @remarks
357 * This is useful if a function requires the node process to limit its
358 * memory so that another spawned process (e.g. a browser instance) can use
359 * the rest.
360 * @public
361 */
362 childProcessMemoryMb?: number;
363 /**
364 * The maximum number of concurrent invocations to allow. Default: 100,
365 * except for the `local` provider, where the default is 10.
366 * @remarks
367 * The concurrency limit applies to all invocations of all of the faast
368 * functions summed together. It is not a per-function limit. To apply a
369 * per-function limit, use {@link throttle}. A value of 0 is equivalent to
370 * Infinity. A value of 1 ensures mutually exclusive invocations.
371 */
372 concurrency?: number;
373 /**
374 * A user-supplied description for this function, which may make it easier
375 * to track different functions when multiple functions are created.
376 */
377 description?: string;
378 /**
379 * Exclude a subset of files included by {@link CommonOptions.include}.
380 * @remarks
381 * The exclusion can be a directory or glob. Exclusions apply to all included
382 * entries.
383 */
384 exclude?: string[];
385 /**
386 * Rate limit invocations (invocations/sec). Default: no rate limit.
387 * @remarks
388 * Some services cannot handle more than a certain number of requests per
389 * second, and it is easy to overwhelm them with a large number of cloud
390 * functions. Specify a rate limit in invocation/second to restrict how
391 * faast.js issues requests.
392 */
393 rate?: number;
394 /**
395 * Environment variables available during serverless function execution.
396 * Default: \{\}.
397 */
398 env?: {
399 [key: string]: string;
400 };
401 /**
402 * Garbage collector mode. Default: `"auto"`.
403 * @remarks
404 * Garbage collection deletes resources that were created by previous
405 * instantiations of faast that were not cleaned up by
406 * {@link FaastModule.cleanup}, either because it was not called or because
407 * the process terminated and did not execute this cleanup step. In `"auto"`
408 * mode, garbage collection may be throttled to run up to once per hour no
409 * matter how many faast.js instances are created. In `"force"` mode,
410 * garbage collection is run without regard to whether another gc has
411 * already been performed recently. In `"off"` mode, garbage collection is
412 * skipped entirely. This can be useful for performance-sensitive tests, or
413 * for more control over when gc is performed.
414 *
415 * Garbage collection is cloud-specific, but in general garbage collection
416 * should not interfere with the behavior or performance of faast cloud
417 * functions. When {@link FaastModule.cleanup} runs, it waits for garbage
418 * collection to complete. Therefore the cleanup step can in some
419 * circumstances take a significant amount of time even after all
420 * invocations have returned.
421 *
422 * It is generally recommended to leave garbage collection in `"auto"` mode,
423 * otherwise garbage resources may accumulate over time and you will
424 * eventually hit resource limits on your account.
425 *
426 * Also see {@link CommonOptions.retentionInDays}.
427 */
428 gc?: "auto" | "force" | "off";
429 /**
430 * Include files to make available in the remote function. See
431 * {@link IncludeOption}.
432 * @remarks
433 * Each include entry is a directory or glob pattern. Paths can be specified
434 * as relative or absolute paths. Relative paths are resolved relative to
435 * the current working directory, or relative to the `cwd` option.
436 *
437 * If the include entry is a directory `"foo/bar"`, the directory
438 * `"./foo/bar"` will be available in the cloud function. Directories are
439 * recursively added.
440 *
441 * Glob patterns use the syntax of
442 * {@link https://github.com/isaacs/node-glob | node glob}.
443 *
444 * Also see {@link CommonOptions.exclude} for file exclusions.
445 */
446 include?: (string | IncludeOption)[];
447 /**
448 * Maximum number of times that faast will retry each invocation. Default: 2
449 * (invocations can therefore be attemped 3 times in total).
450 * @remarks
451 * Retries are automatically attempted for transient infrastructure-level
452 * failures such as rate limits or netowrk failures. User-level exceptions
453 * are not retried automatically. In addition to retries performed by faast,
454 * some providers automatically attempt retries. These are not controllable
455 * by faast. But as a result, your function may be retried many more times
456 * than this setting suggests.
457 */
458 maxRetries?: number;
459 /**
460 * Memory limit for each function in MB. This setting has an effect on
461 * pricing. Default varies by provider.
462 * @remarks
463 * Each provider has different settings for memory size, and performance
464 * varies depending on the setting. By default faast picks a likely optimal
465 * value for each provider.
466 *
467 * - aws: 1728MB
468 *
469 * - google: 1024MB
470 *
471 * - local: 512MB (however, memory size limits aren't reliable in local mode.)
472 */
473 memorySize?: number;
474 /**
475 * Specify invocation mode. Default: `"auto"`.
476 * @remarks
477 * Modes specify how invocations are triggered. In https mode, the functions
478 * are invoked through an https request or the provider's API. In queue
479 * mode, a provider-specific queue is used to invoke functions. Queue mode
480 * adds additional latency and (usually negligible) cost, but may scale
481 * better for some providers. In auto mode the best default is chosen for
482 * each provider depending on its particular performance characteristics.
483 *
484 * The defaults are:
485 *
486 * - aws: `"auto"` is `"https"`. In https mode, the AWS SDK api
487 * is used to invoke functions. In queue mode, an AWS SNS topic is created
488 * and triggers invocations. The AWS API Gateway service is never used by
489 * faast, as it incurs a higher cost and is not needed to trigger
490 * invocations.
491 *
492 * - google: `"auto"` is `"https"`. In https mode, a PUT request is made to
493 * invoke the cloud function. In queue mode, a PubSub topic is created to
494 * invoke functions.
495 *
496 * - local: The local provider ignores the mode setting and always uses an
497 * internal asynchronous queue to schedule calls.
498 *
499 * Size limits are affected by the choice of mode. On AWS the limit is 256kb
500 * for arguments and return values in `"queue"` mode, and 6MB for `"https"`
501 * mode. For Google the limit is 10MB regardless of mode. In Local mode
502 * messages are sent via node's IPC and are subject to OS IPC limits.
503 *
504 * Note that no matter which mode is selected, faast.js always creates a
505 * queue for sending back intermediate results for bookeeping and
506 * performance monitoring.
507 */
508 mode?: "https" | "queue" | "auto";
509 /**
510 * Specify a package.json file to include with the code package.
511 * @remarks
512 * By default, faast.js will use webpack to bundle dependencies your remote
513 * module imports. In normal usage there is no need to specify a separate
514 * package.json, as webpack will statically analyze your imports and
515 * determine which files to bundle.
516 *
517 * However, there are some use cases where this is not enough. For example,
518 * some dependencies contain native code compiled during installation, and
519 * webpack cannot bundle these native modules. such as dependencies with
520 * native code. or are specifically not designed to work with webpack. In
521 * these cases, you can create a separate `package.json` for these
522 * dependencies and pass the filename as the `packageJson` option. If
523 * `packageJson` is an `object`, it is assumed to be a parsed JSON object
524 * with the same structure as a package.json file (useful for specifying a
525 * synthetic `package.json` directly in code).
526 *
527 * The way the `packageJson` is handled varies by provider:
528 *
529 * - local: Runs `npm install` in a temporary directory it prepares for the
530 * function.
531 *
532 * - google: uses Google Cloud Function's
533 * {@link https://cloud.google.com/functions/docs/writing/specifying-dependencies-nodejs | native support for package.json}.
534 *
535 * - aws: Recursively calls faast.js to run `npm install` inside a separate
536 * lambda function specifically created for this purpose. Faast.js uses
537 * lambda to install dependencies to ensure that native dependencies are
538 * compiled in an environment that can produce binaries linked against
539 * lambda's
540 * {@link https://aws.amazon.com/blogs/compute/running-executables-in-aws-lambda/ | execution environment}.
541 * Packages are saved in a Lambda Layer.
542 *
543 * For AWS, if {@link CommonOptions.useDependencyCaching} is `true` (which
544 * is the default), then the Lambda Layer created will be reused in future
545 * function creation requests if the contents of `packageJson` are the same.
546 *
547 * The `FAAST_PACKAGE_DIR` environment variable can be useful for debugging
548 * `packageJson` issues.
549 */
550 packageJson?: string | object;
551 /**
552 * Cache installed dependencies from {@link CommonOptions.packageJson}. Only
553 * applies to AWS. Default: true.
554 * @remarks
555 * If `useDependencyCaching` is `true`, The resulting `node_modules` folder
556 * is cached in a Lambda Layer with the name `faast-${key}`, where `key` is
557 * the SHA1 hash of the `packageJson` contents. These cache entries are
558 * removed by garbage collection, by default after 24h. Using caching
559 * reduces the need to install and upload dependencies every time a function
560 * is created. This is important for AWS because it creates an entirely
561 * separate lambda function to install dependencies remotely, which can
562 * substantially increase function deployment time.
563 *
564 * If `useDependencyCaching` is false, the lambda layer is created with the
565 * same name as the lambda function, and then is deleted when cleanup is
566 * run.
567 */
568 useDependencyCaching?: boolean;
569 /**
570 * Specify how many days to wait before reclaiming cloud garbage. Default:
571 * 1.
572 * @remarks
573 * Garbage collection only deletes resources after they age beyond a certain
574 * number of days. This option specifies how many days old a resource needs
575 * to be before being considered garbage by the collector. Note that this
576 * setting is not recorded when the resources are created. For example,
577 * suppose this is the sequence of events:
578 *
579 * - Day 0: `faast()` is called with `retentionInDays` set to 5. Then, the
580 * function crashes (or omits the call to {@link FaastModule.cleanup}).
581 *
582 * - Day 1: `faast()` is called with `retentionInDays` set to 1.
583 *
584 * In this sequence of events, on Day 0 the garbage collector runs and
585 * removes resources with age older than 5 days. Then the function leaves
586 * new garbage behind because it crashed or did not complete cleanup. On Day
587 * 1, the garbage collector runs and deletes resources at least 1 day old,
588 * which includes garbage left behind from Day 0 (based on the creation
589 * timestamp of the resources). This deletion occurs even though retention
590 * was set to 5 days when resources were created on Day 0.
591 *
592 * On Google, logs are retained according to Google's default expiration
593 * policy (30 days) instead of being deleted by garbage collection.
594 *
595 * Note that if `retentionInDays` is set to 0, garbage collection will
596 * remove all resources, even ones that may be in use by other running faast
597 * instances. Not recommended.
598 *
599 * See {@link CommonOptions.gc}.
600 */
601 retentionInDays?: number;
602 /**
603 * Reduce tail latency by retrying invocations that take substantially
604 * longer than other invocations of the same function. Default: 3.
605 * @remarks
606 * faast.js automatically measures the mean and standard deviation (σ) of
607 * the time taken by invocations of each function. Retries are attempted
608 * when the time for an invocation exceeds the mean time by a certain
609 * threshold. `speculativeRetryThreshold` specifies how many multiples of σ
610 * an invocation needs to exceed the mean for a given function before retry
611 * is attempted.
612 *
613 * The default value of σ is 3. This means a call to a function is retried
614 * when the time to execute exceeds three standard deviations from the mean
615 * of all prior executions of the same function.
616 *
617 * This feature is experimental.
618 * @beta
619 */
620 speculativeRetryThreshold?: number;
621 /**
622 * Execution time limit for each invocation, in seconds. Default: 60.
623 * @remarks
624 * Each provider has a maximum time limit for how long invocations can run
625 * before being automatically terminated (or frozen). The following are the
626 * maximum time limits as of February 2019:
627 *
628 * - aws:
629 * {@link https://docs.aws.amazon.com/lambda/latest/dg/limits.html | 15 minutes}
630 *
631 * - google: {@link https://cloud.google.com/functions/quotas | 9 minutes}
632 *
633 * - local: unlimited
634 *
635 * Faast.js has a proactive timeout detection feature. It automatically
636 * attempts to detect when the time limit is about to be reached and
637 * proactively sends a timeout exception. Faast does this because not all
638 * providers reliably send timely feedback when timeouts occur, leaving
639 * developers to look through cloud logs. In general faast.js' timeout will
640 * be up to 5s earlier than the timeout specified, in order to give time to
641 * allow faast.js to send a timeout message. Proactive timeout detection
642 * only works with {@link CommonOptions.childProcess} set to `true` (the
643 * default).
644 */
645 timeout?: number;
646 /**
647 * Extra webpack options to use to bundle the code package.
648 * @remarks
649 * By default, faast.js uses webpack to bundle the code package. Webpack
650 * automatically handles finding and bundling dependencies, adding source
651 * mappings, etc. If you need specialized bundling, use this option to add
652 * or override the default webpack configuration. The library
653 * {@link https://github.com/survivejs/webpack-merge | webpack-merge} is
654 * used to combine configurations.
655 *
656 * ```typescript
657 * const config: webpack.Configuration = merge({
658 * entry,
659 * mode: "development",
660 * output: {
661 * path: "/",
662 * filename: outputFilename,
663 * libraryTarget: "commonjs2"
664 * },
665 * target: "node",
666 * resolveLoader: { modules: [__dirname, `${__dirname}/dist}`] },
667 * node: { global: true, __dirname: false, __filename: false }
668 * },
669 * webpackOptions);
670 * ```
671 *
672 * Take care when setting the values of `entry`, `output`, or
673 * `resolveLoader`. If these options are overwritten, faast.js may fail to
674 * bundle your code. In particular, setting `entry` to an array value will
675 * help `webpack-merge` to concatenate its value instead of replacing the
676 * value that faast.js inserts for you.
677 *
678 * Default:
679 *
680 * - aws: `{ externals: [new RegExp("^aws-sdk/?")] }`. In the lambda
681 * environment `"aws-sdk"` is available in the ambient environment and
682 * does not need to be bundled.
683 *
684 * - other providers: `{}`
685 *
686 * The `FAAST_PACKAGE_DIR` environment variable can be useful for debugging
687 * webpack issues.
688 */
689 webpackOptions?: webpack.Configuration;
690 /**
691 * Check arguments and return values from cloud functions are serializable
692 * without losing information. Default: true.
693 * @remarks
694 * Arguments to cloud functions are automatically serialized with
695 * `JSON.stringify` with a custom replacer that handles built-in JavaScript
696 * types such as `Date` and `Buffer`. Return values go through the same
697 * process. Some JavaScript objects cannot be serialized. By default
698 * `validateSerialization` will verify that every argument and return value
699 * can be serialized and deserialized without losing information. A
700 * `FaastError` will be thrown if faast.js detects a problem according to
701 * the following procedure:
702 *
703 * 1. Serialize arguments and return values with `JSON.stringify` using a
704 * special `replacer` function.
705 *
706 * 2. Deserialize the values with `JSON.parse` with a special `reviver`
707 * function.
708 *
709 * 3. Use
710 * {@link https://nodejs.org/api/assert.html#assert_assert_deepstrictequal_actual_expected_message | assert.deepStringEqual}
711 * to compare the original object with the deserialized object from step
712 * 2.
713 *
714 * There is some overhead to this process because each argument is
715 * serialized and deserialized, which can be costly if arguments or return
716 * values are large.
717 */
718 validateSerialization?: boolean;
719 /**
720 * Debugging output options.
721 * @internal
722 */
723 debugOptions?: {
724 [key: string]: boolean;
725 };
726}
727
728/**
729 * Analyze the cost of a workload across many provider configurations.
730 * @public
731 */
732export declare namespace CostAnalyzer {
733 /**
734 * An input to {@link CostAnalyzer.analyze}, specifying one
735 * configuration of faast.js to run against a workload. See
736 * {@link AwsOptions} and {@link GoogleOptions}.
737 * @public
738 */
739 export type Configuration = {
740 provider: "aws";
741 options: AwsOptions;
742 } | {
743 provider: "google";
744 options: GoogleOptions;
745 };
746 /**
747 * Default AWS cost analyzer configurations include all memory sizes for AWS
748 * Lambda.
749 * @remarks
750 * The default AWS cost analyzer configurations include every memory size
751 * from 128MB to 3008MB in 64MB increments. Each configuration has the
752 * following settings:
753 *
754 * ```typescript
755 * {
756 * provider: "aws",
757 * options: {
758 * mode: "https",
759 * memorySize,
760 * timeout: 300,
761 * gc: "off",
762 * childProcess: true
763 * }
764 * }
765 * ```
766 *
767 * Use `Array.map` to change or `Array.filter` to remove some of these
768 * configurations. For example:
769 *
770 * ```typescript
771 * const configsWithAtLeast1GB = awsConfigurations.filter(c => c.memorySize > 1024)
772 * const shorterTimeout = awsConfigurations.map(c => ({...c, timeout: 60 }));
773 * ```
774 * @public
775 */
776 const awsConfigurations: Configuration[];
777 /**
778 * Default Google Cloud Functions cost analyzer configurations include all
779 * available memory sizes.
780 * @remarks
781 * Each google cost analyzer configuration follows this template:
782 *
783 * ```typescript
784 * {
785 * provider: "google",
786 * options: {
787 * mode: "https",
788 * memorySize,
789 * timeout: 300,
790 * gc: "off",
791 * childProcess: true
792 * }
793 * }
794 * ```
795 *
796 * where `memorySize` is in `[128, 256, 512, 1024, 2048]`.
797 * @public
798 */
799 const googleConfigurations: Configuration[];
800 /**
801 * User-defined custom metrics for a workload. These are automatically
802 * summarized in the output; see {@link CostAnalyzer.Workload}.
803 * @public
804 */
805 export type WorkloadAttribute<A extends string> = {
806 [attr in A]: number;
807 };
808 /**
809 * A user-defined cost analyzer workload for {@link CostAnalyzer.analyze}.
810 * @public
811 * Example:
812 */
813 export interface Workload<T extends object, A extends string> {
814 /**
815 * The imported module that contains the cloud functions to test.
816 */
817 funcs: T;
818 /**
819 * A function that executes cloud functions on
820 * `faastModule.functions.*`. The work function should return `void` if
821 * there are no custom workload attributes. Otherwise, it should return
822 * a {@link CostAnalyzer.WorkloadAttribute} object which maps
823 * user-defined attribute names to numerical values for the workload.
824 * For example, this might measure bandwidth or some other metric not
825 * tracked by faast.js, but are relevant for evaluating the
826 * cost-performance tradeoff of the configurations analyzed by the cost
827 * analyzer.
828 */
829 work: (faastModule: FaastModule<T>) => Promise<WorkloadAttribute<A> | void>;
830 /**
831 * An array of configurations to run the work function against (see
832 * {@link CostAnalyzer.Configuration}). For example, each entry in the
833 * array may specify a provider, memory size, and other options.
834 * Default: {@link CostAnalyzer.awsConfigurations}.
835 */
836 configurations?: Configuration[];
837 /**
838 * Combine {@link CostAnalyzer.WorkloadAttribute} instances returned
839 * from multiple workload executions (caused by value of
840 * {@link CostAnalyzer.Workload.repetitions}). The default is a function
841 * that takes the average of each attribute.
842 */
843 summarize?: (summaries: WorkloadAttribute<A>[]) => WorkloadAttribute<A>;
844 /**
845 * Format an attribute value for console output. This is displayed by
846 * the cost analyzer when all of the repetitions for a configuration
847 * have completed. The default returns
848 * `${attribute}:${value.toFixed(1)}`.
849 */
850 format?: (attr: A, value: number) => string;
851 /**
852 * Format an attribute value for CSV. The default returns
853 * `value.toFixed(1)`.
854 */
855 formatCSV?: (attr: A, value: number) => string;
856 /**
857 * If true, do not output live results to the console. Can be useful for
858 * running the cost analyzer as part of automated tests. Default: false.
859 */
860 silent?: boolean;
861 /**
862 * The number of repetitions to run the workload for each cost analyzer
863 * configuration. Higher repetitions help reduce the jitter in the
864 * results. Repetitions execute in the same FaastModule instance.
865 * Default: 10.
866 */
867 repetitions?: number;
868 /**
869 * The amount of concurrency to allow. Concurrency can arise from
870 * multiple repetitions of the same configuration, or concurrenct
871 * executions of different configurations. This concurrency limit
872 * throttles the total number of concurrent workload executions across
873 * both of these sources of concurrency. Default: 64.
874 */
875 concurrency?: number;
876 }
877 /**
878 * A cost estimate result for a specific cost analyzer configuration.
879 * @public
880 */
881 export interface Estimate<A extends string> {
882 /**
883 * The cost snapshot for the cost analysis of the specific (workload,
884 * configuration) combination. See {@link CostSnapshot}.
885 */
886 costSnapshot: CostSnapshot;
887 /**
888 * The worload configuration that was analyzed. See
889 * {@link CostAnalyzer.Configuration}.
890 */
891 config: Configuration;
892 /**
893 * Additional workload metrics returned from the work function. See
894 * {@link CostAnalyzer.WorkloadAttribute}.
895 */
896 extraMetrics: WorkloadAttribute<A>;
897 }
898 /**
899 * Estimate the cost of a workload using multiple configurations and
900 * providers.
901 * @param userWorkload - a {@link CostAnalyzer.Workload} object specifying
902 * the workload to run and additional parameters.
903 * @returns A promise for a {@link CostAnalyzer.Result}
904 * @public
905 * @remarks
906 * It can be deceptively difficult to set optimal parameters for AWS Lambda
907 * and similar services. On the surface there appears to be only one
908 * parameter: memory size. Choosing more memory also gives more CPU
909 * performance, but it's unclear how much. It's also unclear where single
910 * core performance stops getting better. The workload cost analyzer solves
911 * these problems by making it easy to run cost experiments.
912 * ```text
913 * (AWS)
914 * ┌───────┐
915 * ┌────▶│ 128MB │
916 * │ └───────┘
917 * │ ┌───────┐
918 * ┌─────────────────┐ ├────▶│ 256MB │
919 * ┌──────────────┐ │ │ │ └───────┘
920 * │ workload │───▶│ │ │ ...
921 * └──────────────┘ │ │ │ ┌───────┐
922 * │ cost analyzer │─────┼────▶│3008MB │
923 * ┌──────────────┐ │ │ │ └───────┘
924 * │configurations│───▶│ │ │
925 * └──────────────┘ │ │ │ (Google)
926 * └─────────────────┘ │ ┌───────┐
927 * ├────▶│ 128MB │
928 * │ └───────┘
929 * │ ┌───────┐
930 * └────▶│ 256MB │
931 * └───────┘
932 * ```
933 * `costAnalyzer` is the entry point. It automatically runs this workload
934 * against multiple configurations in parallel. Then it uses faast.js' cost
935 * snapshot mechanism to automatically determine the price of running the
936 * workload with each configuration.
937 *
938 * Example:
939 *
940 * ```typescript
941 * // functions.ts
942 * export function randomNumbers(n: number) {
943 * let sum = 0;
944 * for (let i = 0; i < n; i++) {
945 * sum += Math.random();
946 * }
947 * return sum;
948 * }
949 *
950 * // cost-analyzer-example.ts
951 * import { writeFileSync } from "fs";
952 * import { CostAnalyzer, FaastModule } from "faastjs";
953 * import * as funcs from "./functions";
954 *
955 * async function work(faastModule: FaastModule<typeof funcs>) {
956 * await faastModule.functions.randomNumbers(100000000);
957 * }
958 *
959 * async function main() {
960 * const results = await CostAnalyzer.analyze({ funcs, work });
961 * writeFileSync("cost.csv", results.csv());
962 * }
963 *
964 * main();
965 * ```
966 *
967 * Example output (this is printed to `console.log` unless the
968 * {@link CostAnalyzer.Workload.silent} is `true`):
969 * ```text
970 * ✔ aws 128MB queue 15.385s 0.274σ $0.00003921
971 * ✔ aws 192MB queue 10.024s 0.230σ $0.00003576
972 * ✔ aws 256MB queue 8.077s 0.204σ $0.00003779
973 * ▲ ▲ ▲ ▲ ▲ ▲
974 * │ │ │ │ │ │
975 * provider │ mode │ stdev average
976 * │ │ execution estimated
977 * memory │ time cost
978 * size │
979 * average cloud
980 * execution time
981 * ```
982 *
983 * The output lists the provider, memory size, ({@link CommonOptions.mode}),
984 * average time of a single execution of the workload, the standard
985 * deviation (in seconds) of the execution time, and average estimated cost
986 * for a single run of the workload.
987 *
988 * The "execution time" referenced here is not wall clock time, but rather
989 * execution time in the cloud function. The execution time does not include
990 * any time the workload spends waiting locally. If the workload invokes
991 * multiple cloud functions, their execution times will be summed even if
992 * they happen concurrently. This ensures the execution time and cost are
993 * aligned.
994 */
995 export function analyze<T extends object, A extends string>(userWorkload: Workload<T, A>): Promise<Result<T, A>>;
996 /**
997 * Cost analyzer results for each workload and configuration.
998 * @remarks
999 * The `estimates` property has the cost estimates for each configuration.
1000 * See {@link CostAnalyzer.Estimate}.
1001 * @public
1002 */
1003 export class Result<T extends object, A extends string> {
1004 /** The workload analyzed. */
1005 readonly workload: Required<Workload<T, A>>;
1006 /**
1007 * Cost estimates for each configuration of the workload. See
1008 * {@link CostAnalyzer.Estimate}.
1009 */
1010 readonly estimates: Estimate<A>[];
1011 /** @internal */
1012 constructor(
1013 /** The workload analyzed. */
1014 workload: Required<Workload<T, A>>,
1015 /**
1016 * Cost estimates for each configuration of the workload. See
1017 * {@link CostAnalyzer.Estimate}.
1018 */
1019 estimates: Estimate<A>[]);
1020 /**
1021 * Comma-separated output of cost analyzer. One line per cost analyzer
1022 * configuration.
1023 * @remarks
1024 * The columns are:
1025 *
1026 * - `memory`: The memory size allocated.
1027 *
1028 * - `cloud`: The cloud provider.
1029 *
1030 * - `mode`: See {@link CommonOptions.mode}.
1031 *
1032 * - `options`: A string summarizing other faast.js options applied to the
1033 * `workload`. See {@link CommonOptions}.
1034 *
1035 * - `completed`: Number of repetitions that successfully completed.
1036 *
1037 * - `errors`: Number of invocations that failed.
1038 *
1039 * - `retries`: Number of retries that were attempted.
1040 *
1041 * - `cost`: The average cost of executing the workload once.
1042 *
1043 * - `executionTime`: the aggregate time spent executing on the provider for
1044 * all cloud function invocations in the workload. This is averaged across
1045 * repetitions.
1046 *
1047 * - `executionTimeStdev`: The standard deviation of `executionTime`.
1048 *
1049 * - `billedTime`: the same as `exectionTime`, except rounded up to the next
1050 * 100ms for each invocation. Usually very close to `executionTime`.
1051 */
1052 csv(): string;
1053 }
1054}
1055
1056/**
1057 * A line item in the cost estimate, including the resource usage metric
1058 * measured and its pricing.
1059 * @public
1060 */
1061export declare class CostMetric {
1062 /** The name of the cost metric, e.g. `functionCallDuration` */
1063 readonly name: string;
1064 /** The price in USD per unit measured. */
1065 readonly pricing: number;
1066 /** The name of the units that pricing is measured in for this metric. */
1067 readonly unit: string;
1068 /** The measured value of the cost metric, in units. */
1069 readonly measured: number;
1070 /**
1071 * The plural form of the unit name. By default the plural form will be the
1072 * name of the unit with "s" appended at the end, unless the last letter is
1073 * capitalized, in which case there is no plural form (e.g. "GB").
1074 */
1075 readonly unitPlural?: string;
1076 /**
1077 * An optional comment, usually providing a link to the provider's pricing
1078 * page and other data.
1079 */
1080 readonly comment?: string;
1081 /**
1082 * True if this cost metric is only for informational purposes (e.g. AWS's
1083 * `logIngestion`) and does not contribute cost.
1084 */
1085 readonly informationalOnly?: boolean;
1086 /** @internal */
1087 constructor(arg: PropertiesExcept<CostMetric, AnyFunction>);
1088 /**
1089 * The cost contribution of this cost metric. Equal to
1090 * {@link CostMetric.pricing} * {@link CostMetric.measured}.
1091 */
1092 cost(): number;
1093 /**
1094 * Return a string with the cost estimate for this metric, omitting
1095 * comments.
1096 */
1097 describeCostOnly(): string;
1098 /** Describe this cost metric, including comments. */
1099 toString(): string;
1100}
1101
1102/**
1103 * A summary of the costs incurred by a faast.js module at a point in time.
1104 * Output of {@link FaastModule.costSnapshot}.
1105 * @remarks
1106 * Cost information provided by faast.js is an estimate. It is derived from
1107 * internal faast.js measurements and not by consulting data provided by your
1108 * cloud provider.
1109 *
1110 * **Faast.js does not guarantee the accuracy of cost estimates.**
1111 *
1112 * **Use at your own risk.**
1113 *
1114 * Example using AWS:
1115 * ```typescript
1116 * const faastModule = await faast("aws", m);
1117 * try {
1118 * // Invoke faastModule.functions.*
1119 * } finally {
1120 * await faastModule.cleanup();
1121 * console.log(`Cost estimate:`);
1122 * console.log(`${await faastModule.costSnapshot()}`);
1123 * }
1124 * ```
1125 *
1126 * AWS example output:
1127 * ```text
1128 * Cost estimate:
1129 * functionCallDuration $0.00002813/second 0.6 second $0.00001688 68.4% [1]
1130 * sqs $0.00000040/request 9 requests $0.00000360 14.6% [2]
1131 * sns $0.00000050/request 5 requests $0.00000250 10.1% [3]
1132 * functionCallRequests $0.00000020/request 5 requests $0.00000100 4.1% [4]
1133 * outboundDataTransfer $0.09000000/GB 0.00000769 GB $0.00000069 2.8% [5]
1134 * logIngestion $0.50000000/GB 0 GB $0 0.0% [6]
1135 * ---------------------------------------------------------------------------------------
1136 * $0.00002467 (USD)
1137 *
1138 * * Estimated using highest pricing tier for each service. Limitations apply.
1139 * ** Does not account for free tier.
1140 * [1]: https://aws.amazon.com/lambda/pricing (rate = 0.00001667/(GB*second) * 1.6875 GB = 0.00002813/second)
1141 * [2]: https://aws.amazon.com/sqs/pricing
1142 * [3]: https://aws.amazon.com/sns/pricing
1143 * [4]: https://aws.amazon.com/lambda/pricing
1144 * [5]: https://aws.amazon.com/ec2/pricing/on-demand/#Data_Transfer
1145 * [6]: https://aws.amazon.com/cloudwatch/pricing/ - Log ingestion costs not currently included.
1146 * ```
1147 *
1148 * A cost snapshot contains several {@link CostMetric} values. Each `CostMetric`
1149 * summarizes one component of the overall cost of executing the functions so
1150 * far. Some cost metrics are common to all faast providers, and other metrics
1151 * are provider-specific. The common metrics are:
1152 *
1153 * - `functionCallDuration`: the estimated billed CPU time (rounded to the next
1154 * 100ms) consumed by completed cloud function calls. This is the metric that
1155 * usually dominates cost.
1156 *
1157 * - `functionCallRequests`: the number of invocation requests made. Most
1158 * providers charge for each invocation.
1159 *
1160 * Provider-specific metrics vary. For example, AWS has the following additional
1161 * metrics:
1162 *
1163 * - `sqs`: AWS Simple Queueing Service. This metric captures the number of
1164 * queue requests made to insert and retrieve queued results (each 64kb chunk
1165 * is counted as an additional request). SQS is used even if
1166 * {@link CommonOptions.mode} is not set to `"queue"`, because it is necessary
1167 * for monitoring cloud function invocations.
1168 *
1169 * - `sns`: AWS Simple Notification Service. SNS is used to invoke Lambda
1170 * functions when {@link CommonOptions.mode} is `"queue"`.
1171 *
1172 * - `outboundDataTransfer`: an estimate of the network data transferred out
1173 * from the cloud provider for this faast.js module. This estimate only counts
1174 * data returned from cloud function invocations and infrastructure that
1175 * faast.js sets up. It does not count any outbound data sent by your cloud
1176 * functions that are not known to faast.js. Note that if you run faast.js on
1177 * EC2 in the same region (see {@link AwsOptions.region}), then the data
1178 * transfer costs will be zero (however, the cost snapshot will not include
1179 * EC2 costs). Also note that if your cloud function transfers data from/to S3
1180 * buckets in the same region, there is no cost as long as that data is not
1181 * returned from the function.
1182 *
1183 * - `logIngestion`: this cost metric is always zero for AWS. It is present to
1184 * remind the user that AWS charges for log data ingested by CloudWatch Logs
1185 * that are not measured by faast.js. Log entries may arrive significantly
1186 * after function execution completes, and there is no way for faast.js to
1187 * know exactly how long to wait, therefore it does not attempt to measure
1188 * this cost. In practice, if your cloud functions do not perform extensive
1189 * logging on all invocations, log ingestion costs from faast.js are likely to
1190 * be low or fall within the free tier.
1191 *
1192 * For Google, extra metrics include `outboundDataTransfer` similar to AWS, and
1193 * `pubsub`, which combines costs that are split into `sns` and `sqs` on AWS.
1194 *
1195 * The Local provider has no extra metrics.
1196 *
1197 * Prices are retrieved dynamically from AWS and Google and cached locally.
1198 * Cached prices expire after 24h. For each cost metric, faast.js uses the
1199 * highest price tier to compute estimated pricing.
1200 *
1201 * Cost estimates do not take free tiers into account.
1202 * @public
1203 */
1204export declare class CostSnapshot {
1205 /** The {@link Provider}, e.g. "aws" or "google" */
1206 readonly provider: string;
1207 /**
1208 * The options used to initialize the faast.js module where this cost
1209 * snapshot was generated.
1210 */
1211 readonly options: CommonOptions | AwsOptions | GoogleOptions;
1212 /** The function statistics that were used to compute prices. */
1213 readonly stats: FunctionStats;
1214 /**
1215 * The cost metric components for this cost snapshot. See
1216 * {@link CostMetric}.
1217 */
1218 readonly costMetrics: CostMetric[];
1219 /** @internal */
1220 constructor(
1221 /** The {@link Provider}, e.g. "aws" or "google" */
1222 provider: string,
1223 /**
1224 * The options used to initialize the faast.js module where this cost
1225 * snapshot was generated.
1226 */
1227 options: CommonOptions | AwsOptions | GoogleOptions, stats: FunctionStats, costMetrics?: CostMetric[]);
1228 /** Sum of cost metrics. */
1229 total(): number;
1230 /** A summary of all cost metrics and prices in this cost snapshot. */
1231 toString(): string;
1232 /**
1233 * Comma separated value output for a cost snapshot.
1234 * @remarks
1235 * The format is "metric,unit,pricing,measured,cost,percentage,comment".
1236 *
1237 * Example output:
1238 * ```text
1239 * metric,unit,pricing,measured,cost,percentage,comment
1240 * functionCallDuration,second,0.00002813,0.60000000,0.00001688,64.1% ,"https://aws.amazon.com/lambda/pricing (rate = 0.00001667/(GB*second) * 1.6875 GB = 0.00002813/second)"
1241 * functionCallRequests,request,0.00000020,5,0.00000100,3.8% ,"https://aws.amazon.com/lambda/pricing"
1242 * outboundDataTransfer,GB,0.09000000,0.00000844,0.00000076,2.9% ,"https://aws.amazon.com/ec2/pricing/on-demand/#Data_Transfer"
1243 * sqs,request,0.00000040,13,0.00000520,19.7% ,"https://aws.amazon.com/sqs/pricing"
1244 * sns,request,0.00000050,5,0.00000250,9.5% ,"https://aws.amazon.com/sns/pricing"
1245 * logIngestion,GB,0.50000000,0,0,0.0% ,"https://aws.amazon.com/cloudwatch/pricing/ - Log ingestion costs not currently included."
1246 * ```
1247 */
1248 csv(): string;
1249 /** @internal */
1250 push(metric: CostMetric): void;
1251 /**
1252 * Find a specific cost metric by name.
1253 * @returns a {@link CostMetric} if found, otherwise `undefined`.
1254 */
1255 find(name: string): CostMetric | undefined;
1256}
1257
1258declare interface CpuMeasurement {
1259 stime: number;
1260 utime: number;
1261 elapsed: number;
1262}
1263
1264declare interface CpuMetricsMessage {
1265 kind: "cpumetrics";
1266 callId: CallId_2;
1267 metrics: CpuMeasurement;
1268}
1269
1270declare class Deferred<T = void> {
1271 promise: Promise<T>;
1272 resolve: (arg: T | PromiseLike<T>) => void;
1273 reject: (err?: any) => void;
1274 constructor();
1275}
1276
1277/**
1278 * A function return value with additional detailed information.
1279 * @public
1280 */
1281export declare interface Detail<R> {
1282 /**
1283 * A Promise for the function's return value.
1284 */
1285 value: R;
1286 /**
1287 * The URL of the logs for the specific execution of this function call.
1288 * @remarks
1289 * This is different from the general logUrl from
1290 * {@link FaastModule.logUrl}, which provides a link to the logs for all
1291 * invocations of all functions within that module. Whereas this logUrl is
1292 * only for this specific invocation.
1293 */
1294 logUrl?: string;
1295 /**
1296 * If available, the provider-specific execution identifier for this
1297 * invocation.
1298 * @remarks
1299 * This ID may be added to the log entries for this invocation by the cloud
1300 * provider.
1301 */
1302 executionId?: string;
1303 /**
1304 * If available, the provider-specific instance identifier for this
1305 * invocation.
1306 * @remarks
1307 * This ID refers to the specific container or VM used to execute this
1308 * function invocation. The instance may be reused across multiple
1309 * invocations.
1310 */
1311 instanceId?: string;
1312}
1313
1314declare type ErrorCallback = (err: Error) => Error;
1315
1316declare interface Executor {
1317 wrapper: Wrapper;
1318 logUrl: string;
1319 logStream?: Writable;
1320}
1321
1322declare type ExtractPropertyNamesExceptType<T, U> = {
1323 [K in keyof T]: T[K] extends U ? never : K;
1324}[keyof T];
1325
1326/**
1327 * The main entry point for faast with any provider and only common options.
1328 * @param provider - One of `"aws"`, `"google"`, or `"local"`. See
1329 * {@link Provider}.
1330 * @param fmodule - A module imported with `import * as X from "Y";`. Using
1331 * `require` also works but loses type information.
1332 * @param options - See {@link CommonOptions}.
1333 * @returns See {@link FaastModule}.
1334 * @remarks
1335 * Example of usage:
1336 * ```typescript
1337 * import { faast } from "faastjs";
1338 * import * as mod from "./path/to/module";
1339 * (async () => {
1340 * const faastModule = await faast("aws", mod);
1341 * try {
1342 * const result = await faastModule.functions.func("arg");
1343 * } finally {
1344 * await faastModule.cleanup();
1345 * }
1346 * })();
1347 * ```
1348 * @public
1349 */
1350export declare function faast<M extends object>(provider: Provider, fmodule: M, options?: CommonOptions): Promise<FaastModule<M>>;
1351
1352/**
1353 * The main entry point for faast with AWS provider.
1354 * @param fmodule - A module imported with `import * as X from "Y";`. Using
1355 * `require` also works but loses type information.
1356 * @param options - Most common options are in {@link CommonOptions}.
1357 * Additional AWS-specific options are in {@link AwsOptions}.
1358 * @public
1359 */
1360export declare function faastAws<M extends object>(fmodule: M, options?: AwsOptions): Promise<AwsFaastModule<M>>;
1361
1362/**
1363 * FaastError is a subclass of VError (https://github.com/joyent/node-verror).
1364 * that is thrown by faast.js APIs and cloud function invocations.
1365 * @remarks
1366 * `FaastError` is a subclass of
1367 * {@link https://github.com/joyent/node-verror | VError}, which provides an API
1368 * for nested error handling. The main API is the same as the standard Error
1369 * class, namely the err.message, err.name, and err.stack properties.
1370 *
1371 * Several static methods on {@link FaastError} are inherited from VError:
1372 *
1373 * FaastError.fullStack(err) - property provides a more detailed stack trace
1374 * that include stack traces of causes in the causal chain.
1375 *
1376 * FaastError.info(err) - returns an object with fields `functionName`, `args`,
1377 * and `logUrl`. The `logUrl` property is a URL pointing to the logs for a
1378 * specific invocation that caused the error.`logUrl` will be surrounded by
1379 * whitespace on both sides to ease parsing as a URL by IDEs.
1380 *
1381 * FaastError.hasCauseWithName(err, cause) - returns true if the FaastError or
1382 * any of its causes includes an error with the given name, otherwise false. All
1383 * of the available names are in the enum {@link FaastErrorNames}. For example,
1384 * to detect if a FaastError was caused by a cloud function timeout:
1385 *
1386 * ```typescript
1387 * FaastError.hasCauseWithName(err, FaastErrorNames.ETIMEOUT)
1388 * ```
1389 *
1390 * FaastError.findCauseByName(err, cause) - like FaastError.hasCauseWithName()
1391 * except it returns the Error in the causal chain with the given name instead
1392 * of a boolean, otherwise null.
1393 *
1394 * @public
1395 */
1396export declare class FaastError extends VError {
1397}
1398
1399/**
1400 * Possible FaastError names. See {@link FaastError}. To test for errors
1401 * matching these names, use the static method
1402 * {@link FaastError}.hasCauseWithName().
1403 * @public
1404 */
1405export declare enum FaastErrorNames {
1406 /** Generic error. See {@link FaastError}. */
1407 EGENERIC = "VError",
1408 /** The arguments passed to the cloud function could not be serialized without losing information. */
1409 ESERIALIZE = "FaastSerializationError",
1410 /** The remote cloud function timed out. */
1411 ETIMEOUT = "FaastTimeoutError",
1412 /** The remote cloud function exceeded memory limits. */
1413 EMEMORY = "FaastOutOfMemoryError",
1414 /** The function invocation was cancelled by user request. */
1415 ECANCEL = "FaastCancelError",
1416 /** The exception was thrown by user's remote code, not by faast.js or the cloud provider. */
1417 EEXCEPTION = "UserException",
1418 /** Could not create the remote cloud function or supporting infrastructure. */
1419 ECREATE = "FaastCreateFunctionError",
1420 /** The remote cloud function failed to execute because of limited concurrency. */
1421 ECONCURRENCY = "FaastConcurrencyError"
1422}
1423
1424/**
1425 * The main entry point for faast with Google provider.
1426 * @param fmodule - A module imported with `import * as X from "Y";`. Using
1427 * `require` also works but loses type information.
1428 * @param options - Most common options are in {@link CommonOptions}.
1429 * Additional Google-specific options are in {@link GoogleOptions}.
1430 * @public
1431 */
1432export declare function faastGoogle<M extends object>(fmodule: M, options?: GoogleOptions): Promise<GoogleFaastModule<M>>;
1433
1434/**
1435 * The main entry point for faast with Local provider.
1436 * @param fmodule - A module imported with `import * as X from "Y";`. Using
1437 * `require` also works but loses type information.
1438 * @param options - Most common options are in {@link CommonOptions}.
1439 * Additional Local-specific options are in {@link LocalOptions}.
1440 * @returns a Promise for {@link LocalFaastModule}.
1441 * @public
1442 */
1443export declare function faastLocal<M extends object>(fmodule: M, options?: LocalOptions): Promise<LocalFaastModule<M>>;
1444
1445/**
1446 * The main interface for invoking, cleaning up, and managing faast.js cloud
1447 * functions. Returned by {@link faast}.
1448 * @public
1449 */
1450export declare interface FaastModule<M extends object> {
1451 /** See {@link Provider}. */
1452 provider: Provider;
1453 /**
1454 * Each call of a cloud function creates a separate remote invocation.
1455 * @remarks
1456 * The module passed into {@link faast} or its provider-specific variants
1457 * ({@link faastAws}, {@link faastGoogle}, and {@link faastLocal}) is mapped
1458 * to a {@link ProxyModule} version of the module, which performs the
1459 * following mapping:
1460 *
1461 * - All function exports that are generators are mapped to async
1462 * generators.
1463 *
1464 * - All function exports that return async generators are preserved as-is.
1465 *
1466 * - All function exports that return promises have their type signatures
1467 * preserved as-is.
1468 *
1469 * - All function exports that return type T, where T is not a Promise,
1470 * Generator, or AsyncGenerator, are mapped to functions that return
1471 * Promise<T>. Argument types are preserved as-is.
1472 *
1473 * - All non-function exports are omitted in the remote module.
1474 *
1475 * Arguments and return values are serialized with `JSON.stringify` when
1476 * cloud functions are called, therefore what is received on the remote side
1477 * might not match what was sent. Faast.js attempts to detect nonsupported
1478 * arguments on a best effort basis.
1479 *
1480 * If the cloud function throws an exception or rejects its promise with an
1481 * instance of `Error`, then the function will reject with
1482 * {@link FaastError} on the local side. If the exception or rejection
1483 * resolves to any value that is not an instance of `Error`, the remote
1484 * function proxy will reject with the value of
1485 * `JSON.parse(JSON.stringify(err))`.
1486 *
1487 * Arguments and return values have size limitations that vary by provider
1488 * and mode:
1489 *
1490 * - AWS: 256KB in queue mode, 6MB arguments and 256KB return values in https mode. See
1491 * {@link https://docs.aws.amazon.com/lambda/latest/dg/limits.html | AWS Lambda Limits}.
1492 *
1493 * - Google: 10MB in https and queue modes. See
1494 * {@link https://cloud.google.com/functions/quotas | Google Cloud Function Quotas}.
1495 *
1496 * - Local: limited only by available memory and the limits of
1497 * {@link https://nodejs.org/api/child_process.html#child_process_subprocess_send_message_sendhandle_options_callback | childprocess.send}.
1498 *
1499 * Note that payloads may be base64 encoded for some providers and therefore
1500 * different in size than the original payload. Also, some bookkeeping data
1501 * are passed along with arguments and contribute to the size limit.
1502 */
1503 functions: ProxyModule<M>;
1504 /**
1505 * Similar to {@link FaastModule.functions} except each function returns a
1506 * {@link Detail} object
1507 * @remarks
1508 * Advanced users of faast.js may want more information about each function
1509 * invocation than simply the result of the function call. For example, the
1510 * specific logUrl for each invocation, to help with detailed debugging.
1511 * This interface provides a way to get this detailed information.
1512 */
1513 functionsDetail: ProxyModuleDetail<M>;
1514 /**
1515 * Stop the faast.js runtime for this cloud function and clean up ephemeral
1516 * cloud resources.
1517 * @returns a Promise that resolves when the `FaastModule` runtime stops and
1518 * ephemeral resources have been deleted.
1519 * @remarks
1520 * It is best practice to always call `cleanup` when done with a cloud
1521 * function. A typical way to ensure this in normal execution is to use the
1522 * `finally` construct:
1523 *
1524 * ```typescript
1525 * const faastModule = await faast("aws", m);
1526 * try {
1527 * // Call faastModule.functions.*
1528 * } finally {
1529 * // Note the `await`
1530 * await faastModule.cleanup();
1531 * }
1532 * ```
1533 *
1534 * After the cleanup promise resolves, the cloud function instance can no
1535 * longer invoke new calls on {@link FaastModule.functions}. However, other
1536 * methods on {@link FaastModule} are safe to call, such as
1537 * {@link FaastModule.costSnapshot}.
1538 *
1539 * Cleanup also stops statistics events (See {@link FaastModule.off}).
1540 *
1541 * By default, cleanup will delete all ephemeral cloud resources but leave
1542 * behind cached resources for use by future cloud functions. Deleted
1543 * resources typically include cloud functions, queues, and queue
1544 * subscriptions. Logs are not deleted by cleanup.
1545 *
1546 * Note that `cleanup` leaves behind some provider-specific resources:
1547 *
1548 * - AWS: Cloudwatch logs are preserved until the garbage collector in a
1549 * future cloud function instance deletes them. The default log expiration
1550 * time is 24h (or the value of {@link CommonOptions.retentionInDays}). In
1551 * addition, the AWS Lambda IAM role is not deleted by cleanup. This role
1552 * is shared across cloud function instances. Lambda layers are also not
1553 * cleaned up immediately on AWS when {@link CommonOptions.packageJson} is
1554 * used and {@link CommonOptions.useDependencyCaching} is true. Cached
1555 * layers are cleaned up by garbage collection. Also see
1556 * {@link CleanupOptions.deleteCaches}.
1557 *
1558 * - Google: Google Stackdriver automatically deletes log entries after 30
1559 * days.
1560 *
1561 * - Local: Logs are preserved in a temporary directory on local disk.
1562 * Garbage collection in a future cloud function instance will delete logs
1563 * older than 24h.
1564 */
1565 cleanup(options?: CleanupOptions): Promise<void>;
1566 /**
1567 * The URL of logs generated by this cloud function.
1568 * @remarks
1569 * Logs are not automatically downloaded because they cause outbound data
1570 * transfer, which can be expensive. Also, logs may arrive at the logging
1571 * service well after the cloud functions have completed. This log URL
1572 * specifically filters the logs for this cloud function instance.
1573 * Authentication is required to view cloud provider logs.
1574 *
1575 * The local provider returns a `file://` url pointing to a file for logs.
1576 */
1577 logUrl(): string;
1578 /**
1579 * Register a callback for statistics events.
1580 * @remarks
1581 * The callback is invoked once for each cloud function that was invoked
1582 * within the last 1s interval, with a {@link FunctionStatsEvent}
1583 * summarizing the statistics for each function. Typical usage:
1584 *
1585 * ```typescript
1586 * faastModule.on("stats", console.log);
1587 * ```
1588 */
1589 on(name: "stats", listener: (statsEvent: FunctionStatsEvent) => void): void;
1590 /**
1591 * Deregister a callback for statistics events.
1592 * @remarks
1593 * Stops the callback listener from receiving future function statistics
1594 * events. Calling {@link FaastModule.cleanup} also turns off statistics
1595 * events.
1596 */
1597 off(name: "stats", listener: (statsEvent: FunctionStatsEvent) => void): void;
1598 /**
1599 * Get a near real-time cost estimate of cloud function invocations.
1600 * @returns a Promise for a {@link CostSnapshot}.
1601 * @remarks
1602 * A cost snapshot provides a near real-time estimate of the costs of the
1603 * cloud functions invoked. The cost estimate only includes the cost of
1604 * successfully completed calls. Unsuccessful calls may lack the data
1605 * required to provide cost information. Calls that are still in flight are
1606 * not included in the cost snapshot. For this reason, it is typically a
1607 * good idea to get a cost snapshot after awaiting the result of
1608 * {@link FaastModule.cleanup}.
1609 *
1610 * Code example:
1611 *
1612 * ```typescript
1613 * const faastModule = await faast("aws", m);
1614 * try {
1615 * // invoke cloud functions on faastModule.functions.*
1616 * } finally {
1617 * await faastModule.cleanup();
1618 * const costSnapshot = await faastModule.costSnapshot();
1619 * console.log(costSnapshot);
1620 * }
1621 * ```
1622 */
1623 costSnapshot(): Promise<CostSnapshot>;
1624 /**
1625 * Statistics for a specific function or the entire faast.js module.
1626 *
1627 * @param functionName - The name of the function to retrieve statistics
1628 * for. If the function does not exist or has not been invoked, a new
1629 * instance of {@link FunctionStats} is returned with zero values. If
1630 * `functionName` omitted (undefined), then aggregate statistics are
1631 * returned that summarize all cloud functions within this faast.js module.
1632 * @returns an snapshot of {@link FunctionStats} at a point in time.
1633 */
1634 stats(functionName?: string): FunctionStats;
1635}
1636
1637/**
1638 * Implementation of {@link FaastModule}.
1639 * @remarks
1640 * `FaastModuleProxy` provides a unified developer experience for faast.js
1641 * modules on top of provider-specific runtime APIs. Most users will not create
1642 * `FaastModuleProxy` instances themselves; instead use {@link faast}, or
1643 * {@link faastAws}, {@link faastGoogle}, or {@link faastLocal}.
1644 * `FaastModuleProxy` implements the {@link FaastModule} interface, which is the
1645 * preferred public interface for faast modules. `FaastModuleProxy` can be used
1646 * to access provider-specific details and state, and is useful for deeper
1647 * testing.
1648 * @public
1649 */
1650export declare class FaastModuleProxy<M extends object, O, S> implements FaastModule<M> {
1651 private impl;
1652 /** @internal */
1653 readonly state: S;
1654 private fmodule;
1655 private modulePath;
1656 /** The options set for this instance, which includes default values. */
1657 readonly options: Required<CommonOptions>;
1658 /** The {@link Provider}, e.g. "aws" or "google". */
1659 provider: Provider;
1660 /** {@inheritdoc FaastModule.functions} */
1661 functions: ProxyModule<M>;
1662 /** {@inheritdoc FaastModule.functionsDetail} */
1663 functionsDetail: ProxyModuleDetail<M>;
1664 /** @internal */
1665 private _stats;
1666 private _cpuUsage;
1667 private _memoryLeakDetector;
1668 private _funnel;
1669 private _rateLimiter?;
1670 private _skew;
1671 private _statsTimer?;
1672 private _cleanupHooks;
1673 private _initialInvocationTime;
1674 private _callResultsPending;
1675 private _collectorPump;
1676 private _emitter;
1677 /**
1678 * Constructor
1679 * @internal
1680 */
1681 constructor(impl: ProviderImpl<O, S>,
1682 /** @internal */
1683 state: S, fmodule: M, modulePath: string,
1684 /** The options set for this instance, which includes default values. */
1685 options: Required<CommonOptions>);
1686 /** {@inheritdoc FaastModule.cleanup} */
1687 cleanup(userCleanupOptions?: CleanupOptions): Promise<void>;
1688 /** {@inheritdoc FaastModule.logUrl} */
1689 logUrl(): string;
1690 private startStats;
1691 private stopStats;
1692 /** {@inheritdoc FaastModule.on} */
1693 on(name: "stats", listener: (statsEvent: FunctionStatsEvent) => void): void;
1694 /** {@inheritdoc FaastModule.off} */
1695 off(name: "stats", listener: (statsEvent: FunctionStatsEvent) => void): void;
1696 private withCancellation;
1697 private processResponse;
1698 private invoke;
1699 private lookupFname;
1700 private createCallId;
1701 private wrapGenerator;
1702 private clearPending;
1703 private wrapFunction;
1704 /** {@inheritdoc FaastModule.costSnapshot} */
1705 costSnapshot(): Promise<CostSnapshot>;
1706 /** {@inheritdoc FaastModule.stats} */
1707 stats(functionName?: string): FunctionStats;
1708 private resultCollector;
1709 private adjustCollectorConcurrencyLevel;
1710}
1711
1712declare interface FunctionCall extends CallId {
1713 args: string;
1714 modulePath: string;
1715 name: string;
1716 ResponseQueueId: string;
1717}
1718
1719declare interface FunctionStartedMessage {
1720 kind: "functionstarted";
1721 callId: CallId_2;
1722}
1723
1724/**
1725 * Summary statistics for function invocations.
1726 * @remarks
1727 * ```
1728 * localStartLatency remoteStartLatency executionTime
1729 * ◀──────────────────▶◁ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ▷◀──────────▶
1730 *
1731 * ┌───────────────────────────────────┬──────────────────────────────────────┐
1732 * │ │ │
1733 * │ Local │ Cloud Provider │
1734 * │ │ │
1735 * │ ┌─────────┐ │ ┌──────────┐ ┌──────────┐ │
1736 * │ │ │ │ │ │ │ │ │
1737 * │ │ local │ │ │ request │ │ │ │
1738 * │ invoke ────────▶│ queue │────┼──▶│ queue ├────────▶│ │ │
1739 * │ │ │ │ │ │ │ │ │
1740 * │ └─────────┘ │ └──────────┘ │ cloud │ │
1741 * │ │ │ function │ │
1742 * │ ┌─────────┐ │ ┌──────────┐ │ │ │
1743 * │ │ │ │ │ │ │ │ │
1744 * │ result ◀────────│ local │◀───┼───│ response │◀────────│ │ │
1745 * │ │ polling │ │ │ queue │ │ │ │
1746 * │ │ │ │ │ │ │ │ │
1747 * │ └─────────┘ │ └──────────┘ └──────────┘ │
1748 * │ │ │
1749 * └───────────────────────────────────┴──────────────────────────────────────┘
1750 *
1751 * ◁ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ▷
1752 * returnLatency ◀───────▶
1753 * sendResponseLatency
1754 * ```
1755 *
1756 * `localStartLatency` and `executionTime` are measured on one machine and are
1757 * free of clock skew. `remoteStartLatency` and `returnLatency` are measured as
1758 * time differences between machines and are subject to much more uncertainty,
1759 * and effects like clock skew.
1760 *
1761 * All times are in milliseconds.
1762 *
1763 * @public
1764 */
1765export declare class FunctionStats {
1766 /**
1767 * Statistics for how long invocations stay in the local queue before being
1768 * sent to the cloud provider.
1769 */
1770 localStartLatency: Statistics;
1771 /**
1772 * Statistics for how long requests take to start execution after being sent
1773 * to the cloud provider. This typically includes remote queueing and cold
1774 * start times. Because this measurement requires comparing timestamps from
1775 * different machines, it is subject to clock skew and other effects, and
1776 * should not be considered highly accurate. It can be useful for detecting
1777 * excessively high latency problems. Faast.js attempt to correct for clock
1778 * skew heuristically.
1779 */
1780 remoteStartLatency: Statistics;
1781 /**
1782 * Statistics for function execution time in milliseconds. This is measured
1783 * as wall clock time inside the cloud function, and does not include the
1784 * time taken to send the response to the response queue. Note that most
1785 * cloud providers round up to the next 100ms for pricing.
1786 */
1787 executionTime: Statistics;
1788 /**
1789 * Statistics for how long it takes to send the response to the response
1790 * queue.
1791 */
1792 sendResponseLatency: Statistics;
1793 /**
1794 * Statistics for how long it takes to return a response from the end of
1795 * execution time to the receipt of the response locally. This measurement
1796 * requires comparing timestamps from different machines, and is subject to
1797 * clock skew and other effects. It should not be considered highly
1798 * accurate. It can be useful for detecting excessively high latency
1799 * problems. Faast.js attempts to correct for clock skew heuristically.
1800 */
1801 returnLatency: Statistics;
1802 /**
1803 * Statistics for amount of time billed. This is similar to
1804 * {@link FunctionStats.executionTime} except each sampled time is rounded
1805 * up to the next 100ms.
1806 */
1807 estimatedBilledTime: Statistics;
1808 /**
1809 * The number of invocations attempted. If an invocation is retried, this
1810 * only counts the invocation once.
1811 */
1812 invocations: number;
1813 /**
1814 * The number of invocations that were successfully completed.
1815 */
1816 completed: number;
1817 /**
1818 * The number of invocation retries attempted. This counts retries
1819 * attempted by faast.js to recover from transient errors, but does not
1820 * count retries by the cloud provider.
1821 */
1822 retries: number;
1823 /**
1824 * The number of invocations that resulted in an error. If an invocation is
1825 * retried, an error is only counted once, no matter how many retries were
1826 * attempted.
1827 */
1828 errors: number;
1829 /**
1830 * Summarize the function stats as a string.
1831 * @returns a string showing the value of completed, retries, errors, and
1832 * mean execution time. This string excludes invocations by default because
1833 * it is often fixed.
1834 */
1835 toString(): string;
1836 /** @internal */
1837 clone(): FunctionStats;
1838}
1839
1840/**
1841 * Summarize statistics about cloud function invocations.
1842 * @public
1843 */
1844export declare class FunctionStatsEvent {
1845 /** The name of the cloud function the statistics are about. */
1846 readonly fn: string;
1847 /** See {@link FunctionStats}. */
1848 readonly stats: FunctionStats;
1849 /**
1850 * @internal
1851 */
1852 constructor(
1853 /** The name of the cloud function the statistics are about. */
1854 fn: string,
1855 /** See {@link FunctionStats}. */
1856 stats: FunctionStats);
1857 /**
1858 * Returns a string summarizing the statistics event.
1859 * @remarks
1860 * The string includes number of completed calls, errors, and retries, and
1861 * the mean execution time for the calls that completed within the last time
1862 * interval (1s).
1863 */
1864 toString(): string;
1865}
1866
1867/**
1868 * The return type of {@link faastGoogle}. See {@link FaastModuleProxy}.
1869 * @public
1870 */
1871export declare type GoogleFaastModule<M extends object = object> = FaastModuleProxy<M, GoogleOptions, GoogleState>;
1872
1873declare class GoogleMetrics {
1874 outboundBytes: number;
1875 pubSubBytes: number;
1876}
1877
1878/**
1879 * Google-specific options for {@link faastGoogle}.
1880 * @public
1881 */
1882export declare interface GoogleOptions extends CommonOptions {
1883 /**
1884 * The region to create resources in. Garbage collection is also limited to
1885 * this region. Default: `"us-central1"`.
1886 */
1887 region?: GoogleRegion;
1888 /**
1889 * Additional options to pass to Google Cloud Function creation. See
1890 * {@link https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions#CloudFunction | projects.locations.functions}.
1891 * @remarks
1892 * If you need specialized options, you can pass them to the Google Cloud
1893 * Functions API directly. Note that if you override any settings set by
1894 * faast.js, you may cause faast.js to not work:
1895 *
1896 * ```typescript
1897 * const requestBody: CloudFunctions.Schema$CloudFunction = {
1898 * name,
1899 * entryPoint: "trampoline",
1900 * timeout,
1901 * availableMemoryMb,
1902 * sourceUploadUrl,
1903 * runtime: "nodejs14",
1904 * ...googleCloudFunctionOptions
1905 * };
1906 * ```
1907 *
1908 */
1909 googleCloudFunctionOptions?: cloudfunctions_v1.Schema$CloudFunction;
1910 /** @internal */
1911 _gcWorker?: (resources: GoogleResources, services: GoogleServices) => Promise<void>;
1912}
1913
1914/**
1915 * Valid Google Cloud
1916 * {@link https://cloud.google.com/compute/docs/regions-zones/ | regions}. Only
1917 * some of these
1918 * {@link https://cloud.google.com/functions/docs/locations | regions have Cloud Functions}.
1919 * @public
1920 */
1921export declare type GoogleRegion = "asia-east1" | "asia-east2" | "asia-northeast1" | "asia-south1" | "asia-southeast1" | "australia-southeast1" | "europe-north1" | "europe-west1" | "europe-west2" | "europe-west3" | "europe-west4" | "europe-west6" | "northamerica-northeast1" | "southamerica-east1" | "us-central1" | "us-east1" | "us-east4" | "us-west1" | "us-west2";
1922
1923declare interface GoogleResources {
1924 trampoline: string;
1925 requestQueueTopic?: string;
1926 requestSubscription?: string;
1927 responseQueueTopic?: string;
1928 responseSubscription?: string;
1929 region: string;
1930}
1931
1932declare interface GoogleServices {
1933 readonly cloudFunctions: cloudfunctions_v1.Cloudfunctions;
1934 readonly pubsub: pubsub_v1.Pubsub;
1935 readonly google: GoogleApis;
1936 readonly cloudBilling: cloudbilling_v1.Cloudbilling;
1937}
1938
1939/**
1940 * @internal
1941 */
1942declare interface GoogleState {
1943 resources: GoogleResources;
1944 services: GoogleServices;
1945 url?: string;
1946 project: string;
1947 functionName: string;
1948 metrics: GoogleMetrics;
1949 options: Required<GoogleOptions>;
1950 gcPromise?: Promise<void>;
1951}
1952
1953/**
1954 * Options for the {@link CommonOptions.include} option.
1955 * @public
1956 */
1957export declare interface IncludeOption {
1958 /**
1959 * The path to the directory or glob to add to the cloud function.
1960 */
1961 path: string;
1962 /**
1963 * The working directory if `path` is relative. Defaults to `process.cwd()`.
1964 * For example, if `cwd` is `"foo"` and `path` is `"bar"`, then the
1965 * contents of the directory `foo/bar/` will be added to the remote
1966 * function under the path `bar/`.
1967 */
1968 cwd?: string;
1969}
1970
1971declare interface IteratorResponseMessage extends ResponseContext {
1972 kind: "iterator";
1973 sequence: number;
1974}
1975
1976/**
1977 * Specify {@link throttle} limits. These limits shape the way throttle invokes
1978 * the underlying function.
1979 * @public
1980 */
1981export declare interface Limits {
1982 /**
1983 * The maximum number of concurrent executions of the underlying function to
1984 * allow. Must be supplied, there is no default. Specifying `0` or
1985 * `Infinity` is allowed and means there is no concurrency limit.
1986 */
1987 concurrency: number;
1988 /**
1989 * The maximum number of calls per second to allow to the underlying
1990 * function. Default: no rate limit.
1991 */
1992 rate?: number;
1993 /**
1994 * The maximum number of calls to the underlying function to "burst" -- e.g.
1995 * the number that can be issued immediately as long as the rate limit is
1996 * not exceeded. For example, if rate is 5 and burst is 5, and 10 calls are
1997 * made to the throttled function, 5 calls are made immediately and then
1998 * after 1 second, another 5 calls are made immediately. Setting burst to 1
1999 * means calls are issued uniformly every `1/rate` seconds. If `rate` is not
2000 * specified, then `burst` does not apply. Default: 1.
2001 */
2002 burst?: number;
2003 /**
2004 * Retry if the throttled function returns a rejected promise. `retry` can
2005 * be a number or a function. If it is a number `N`, then up to `N`
2006 * additional attempts are made in addition to the initial call. If retry is
2007 * a function, it should return `true` if another retry attempt should be
2008 * made, otherwise `false`. The first argument will be the value of the
2009 * rejected promise from the previous call attempt, and the second argument
2010 * will be the number of previous retry attempts (e.g. the first call will
2011 * have value 0). Default: 0 (no retry attempts).
2012 */
2013 retry?: number | ((err: any, retries: number) => boolean);
2014 /**
2015 * If `memoize` is `true`, then every call to the throttled function will be
2016 * saved as an entry in a map from arguments to return value. If same
2017 * arguments are seen again in a future call, the return value is retrieved
2018 * from the Map rather than calling the function again. This can be useful
2019 * for avoiding redundant calls that are expected to return the same results
2020 * given the same arguments.
2021 *
2022 * The arguments will be captured with `JSON.stringify`, therefore types
2023 * that do not stringify uniquely won't be distinguished from each other.
2024 * Care must be taken when specifying `memoize` to ensure avoid incorrect
2025 * results.
2026 */
2027 memoize?: boolean;
2028 /**
2029 * Similar to `memoize` except the map from function arguments to results is
2030 * stored in a persistent cache on disk. This is useful to prevent redundant
2031 * calls to APIs which are expected to return the same results for the same
2032 * arguments, and which are likely to be called across many faast.js module
2033 * instantiations. This is used internally by faast.js for caching cloud
2034 * prices for AWS and Google, and for saving the last garbage collection
2035 * date for AWS. Persistent cache entries expire after a period of time. See
2036 * {@link PersistentCache}.
2037 */
2038 cache?: PersistentCache;
2039 /**
2040 * A promise that, if resolved, causes cancellation of pending throttled
2041 * invocations. This is typically created using `Deferred`. The idea is to
2042 * use the resolving of the promise as an asynchronous signal that any
2043 * pending invocations in this throttled function should be cleared.
2044 * @internal
2045 */
2046 cancel?: Promise<void>;
2047}
2048
2049/**
2050 * The return type of {@link faastLocal}. See {@link FaastModuleProxy}.
2051 * @public
2052 */
2053export declare type LocalFaastModule<M extends object = object> = FaastModuleProxy<M, LocalOptions, LocalState>;
2054
2055/**
2056 * Local provider options for {@link faastLocal}.
2057 *
2058 * @public
2059 */
2060export declare interface LocalOptions extends CommonOptions {
2061 /** @internal */
2062 _gcWorker?: (tempdir: string) => Promise<void>;
2063}
2064
2065/**
2066 * @public
2067 */
2068declare interface LocalState {
2069 /** @internal */
2070 executors: Executor[];
2071 /** @internal */
2072 getExecutor: () => Executor;
2073 /** The temporary directory where the local function is deployed. */
2074 tempDir: string;
2075 /** The file:// URL for the local function log file directory. */
2076 logUrl: string;
2077 /** @internal */
2078 gcPromise?: Promise<void>;
2079 /** @internal */
2080 queue: AsyncQueue<Message>;
2081 /** Options used to initialize the local function. */
2082 options: Required<LocalOptions>;
2083}
2084
2085/**
2086 * Faast.js loggers.
2087 * @remarks
2088 * Unless otherwise specified, each log is disabled by default unless the value
2089 * of the DEBUG environment variable is set to the corresponding value. For
2090 * example:
2091 *
2092 * ```
2093 * $ DEBUG=faast:info,faast:provider <cmd>
2094 * $ DEBUG=faast:* <cmd>
2095 * ```
2096 *
2097 * Logs can also be enabled or disabled programmatically:
2098 * ```typescript
2099 * import { log } from "faastjs"
2100 * log.info.enabled = true;
2101 * log.provider.enabled = true;
2102 * ```
2103 *
2104 * Each log outputs specific information:
2105 *
2106 * `info` - General informational logging.
2107 *
2108 * `minimal` - Outputs only basic information like the function name created in
2109 * the cloud.
2110 *
2111 * `warn` - Warnings. Enabled by default.
2112 *
2113 * `gc` - Garbage collection verbose logging.
2114 *
2115 * `leaks` - Memory leak detector warnings for the cloud function. Enabled by
2116 * default.
2117 *
2118 * `calls` - Verbose logging of each faast.js enabled function invocation.
2119 *
2120 * `webpack` - Verbose logging from webpack and packaging details.
2121 *
2122 * `provider` - Verbose logging of each interaction between faast.js runtime and
2123 * the provider-specific implementation.
2124 *
2125 * `awssdk` - Verbose logging of AWS SDK. This can be useful for identifying
2126 * which API calls are failing, retrying, or encountering rate limits.
2127 *
2128 * @public
2129 */
2130export declare const log: {
2131 info: debug_2.Debugger;
2132 minimal: debug_2.Debugger;
2133 warn: debug_2.Debugger;
2134 gc: debug_2.Debugger;
2135 leaks: debug_2.Debugger;
2136 calls: debug_2.Debugger;
2137 webpack: debug_2.Debugger;
2138 provider: debug_2.Debugger;
2139 awssdk: debug_2.Debugger;
2140};
2141
2142declare type Message = PromiseResponseMessage | IteratorResponseMessage | FunctionStartedMessage | CpuMetricsMessage;
2143
2144declare type MessageCallback = (msg: Message) => Promise<void>;
2145
2146declare interface ModuleType {
2147 [name: string]: any;
2148}
2149
2150/**
2151 * A simple persistent key-value store. Used to implement {@link Limits.cache}
2152 * for {@link throttle}.
2153 * @remarks
2154 * Entries can be expired, but are not actually deleted individually. The entire
2155 * cache can be deleted at once. Hence this cache is useful for storing results
2156 * that are expensive to compute but do not change too often (e.g. the
2157 * node_modules folder from an 'npm install' where 'package.json' is not
2158 * expected to change too often).
2159 *
2160 * By default faast.js will use the directory `~/.faastjs` as a local cache to
2161 * store data such as pricing retrieved from cloud APIs, and garbage collection
2162 * information. This directory can be safely deleted if no faast.js instances
2163 * are running.
2164 * @public
2165 */
2166export declare class PersistentCache {
2167 /**
2168 * The directory under the user's home directory that will be used to
2169 * store cached values. The directory will be created if it doesn't
2170 * exist.
2171 */
2172 readonly dirRelativeToHomeDir: string;
2173 /**
2174 * The age (in ms) after which a cached entry is invalid. Default:
2175 * `24*3600*1000` (1 day).
2176 */
2177 readonly expiration: number;
2178 private initialized;
2179 private initialize;
2180 /**
2181 * The directory on disk where cached values are stored.
2182 */
2183 readonly dir: string;
2184 /**
2185 * Construct a new persistent cache, typically used with {@link Limits} as
2186 * part of the arguments to {@link throttle}.
2187 * @param dirRelativeToHomeDir - The directory under the user's home
2188 * directory that will be used to store cached values. The directory will be
2189 * created if it doesn't exist.
2190 * @param expiration - The age (in ms) after which a cached entry is
2191 * invalid. Default: `24*3600*1000` (1 day).
2192 */
2193 constructor(
2194 /**
2195 * The directory under the user's home directory that will be used to
2196 * store cached values. The directory will be created if it doesn't
2197 * exist.
2198 */
2199 dirRelativeToHomeDir: string,
2200 /**
2201 * The age (in ms) after which a cached entry is invalid. Default:
2202 * `24*3600*1000` (1 day).
2203 */
2204 expiration?: number);
2205 /**
2206 * Retrieves the value previously set for the given key, or undefined if the
2207 * key is not found.
2208 */
2209 get(key: string): Promise<Buffer | undefined>;
2210 /**
2211 * Set the cache key to the given value.
2212 * @returns a Promise that resolves when the cache entry has been persisted.
2213 */
2214 set(key: string, value: Buffer | string | Uint8Array | Readable | Blob_2): Promise<void>;
2215 /**
2216 * Retrieve all keys stored in the cache, including expired entries.
2217 */
2218 entries(): Promise<string[]>;
2219 /**
2220 * Deletes all cached entries from disk.
2221 * @param leaveEmptyDir - If true, leave the cache directory in place after
2222 * deleting its contents. If false, the cache directory will be removed.
2223 * Default: `true`.
2224 */
2225 clear({ leaveEmptyDir }?: {
2226 leaveEmptyDir?: boolean | undefined;
2227 }): Promise<void>;
2228}
2229
2230declare interface PollResult {
2231 Messages: Message[];
2232 isFullMessageBatch?: boolean;
2233}
2234
2235declare interface PromiseResponseMessage extends ResponseContext {
2236 kind: "promise";
2237}
2238
2239declare type PropertiesExcept<T, X> = Pick<T, ExtractPropertyNamesExceptType<T, X>>;
2240
2241/**
2242 * The type of all supported cloud providers.
2243 * @public
2244 */
2245export declare type Provider = "aws" | "google" | "local";
2246
2247declare interface ProviderImpl<O extends CommonOptions, S> {
2248 name: Provider;
2249 defaults: Required<O>;
2250 initialize(serverModule: string, nonce: UUID, options: Required<O>): Promise<S>;
2251 costSnapshot(state: S, stats: FunctionStats): Promise<CostSnapshot>;
2252 cleanup(state: S, options: Required<CleanupOptions>): Promise<void>;
2253 logUrl(state: S): string;
2254 invoke(state: S, request: FunctionCall, cancel: Promise<void>): Promise<void>;
2255 poll(state: S, cancel: Promise<void>): Promise<PollResult>;
2256 responseQueueId(state: S): string;
2257}
2258
2259/**
2260 * An array of all available provider.
2261 * @public
2262 */
2263export declare const providers: Provider[];
2264
2265/**
2266 * `ProxyModule<M>` is the type of {@link FaastModule.functions}.
2267 * @remarks
2268 * `ProxyModule<M>` maps an imported module's functions to promise-returning or
2269 * async-iteratable versions of those functions. Non-function exports of the
2270 * module are omitted. When invoked, the functions in a `ProxyModule` invoke a
2271 * remote cloud function.
2272 * @public
2273 */
2274export declare type ProxyModule<M> = {
2275 [K in keyof M]: M[K] extends (...args: infer A) => infer R ? (...args: A) => Async<R> : never;
2276};
2277
2278/**
2279 * Similar to {@link ProxyModule} except each function returns a {@link Detail}
2280 * object.
2281 * @remarks
2282 * See {@link FaastModule.functionsDetail}.
2283 * @public
2284 */
2285export declare type ProxyModuleDetail<M> = {
2286 [K in keyof M]: M[K] extends (...args: infer A) => infer R ? (...args: A) => AsyncDetail<R> : never;
2287};
2288
2289declare interface ResponseContext {
2290 type: "fulfill" | "reject";
2291 value: string;
2292 callId: CallId_2;
2293 isErrorObject?: boolean;
2294 remoteExecutionStartTime?: number;
2295 remoteExecutionEndTime?: number;
2296 logUrl?: string;
2297 instanceId?: string;
2298 executionId?: string;
2299 memoryUsage?: NodeJS.MemoryUsage;
2300 timestamp?: number;
2301}
2302
2303/**
2304 * Incrementally updated statistics on a set of values.
2305 * @public
2306 */
2307export declare class Statistics {
2308 /** The number of decimal places to print in {@link Statistics.toString} */
2309 protected printFixedPrecision: number;
2310 /** Number of values observed. */
2311 samples: number;
2312 /** The maximum value observed. Initialized to `Number.NEGATIVE_INFINITY`. */
2313 max: number;
2314 /** The minimum value observed. Initialized to `Number.POSITIVE_INFINITY`. */
2315 min: number;
2316 /** The variance of the values observed. */
2317 variance: number;
2318 /** The standard deviation of the values observed. */
2319 stdev: number;
2320 /** The mean (average) of the values observed. */
2321 mean: number;
2322 /**
2323 * Incrementally track mean, stdev, min, max, of a sequence of values.
2324 * @param printFixedPrecision - The number of decimal places to print in
2325 * {@link Statistics.toString}.
2326 */
2327 constructor(
2328 /** The number of decimal places to print in {@link Statistics.toString} */
2329 printFixedPrecision?: number);
2330 /** @internal */
2331 clone(): Statistics & this;
2332 /**
2333 * Update statistics with a new value in the sequence.
2334 */
2335 update(value: number | undefined): void;
2336 /**
2337 * Print the mean of the observations seen, with the precision specified in
2338 * the constructor.
2339 */
2340 toString(): string;
2341}
2342
2343/**
2344 * A decorator for rate limiting, concurrency limiting, retry, memoization, and
2345 * on-disk caching. See {@link Limits}.
2346 * @remarks
2347 * When programming against cloud services, databases, and other resources, it
2348 * is often necessary to control the rate of request issuance to avoid
2349 * overwhelming the service provider. In many cases the provider has built-in
2350 * safeguards against abuse, which automatically fail requests if they are
2351 * coming in too fast. Some systems don't have safeguards and precipitously
2352 * degrade their service level or fail outright when faced with excessive load.
2353 *
2354 * With faast.js it becomes very easy to (accidentally) generate requests from
2355 * thousands of cloud functions. The `throttle` function can help manage request
2356 * flow without resorting to setting up a separate service. This is in keeping
2357 * with faast.js' zero-ops philosophy.
2358 *
2359 * Usage is simple:
2360 *
2361 * ```typescript
2362 * async function operation() { ... }
2363 * const throttledOperation = throttle({ concurrency: 10, rate: 5 }, operation);
2364 * for(let i = 0; i < 100; i++) {
2365 * // at most 10 concurrent executions at a rate of 5 invocations per second.
2366 * throttledOperation();
2367 * }
2368 * ```
2369 *
2370 * Note that each invocation to `throttle` creates a separate function with a
2371 * separate limits. Therefore it is likely that you want to use `throttle` in a
2372 * global context, not within a dynamic context:
2373 *
2374 * ```typescript
2375 * async function operation() { ... }
2376 * for(let i = 0; i < 100; i++) {
2377 * // WRONG - each iteration creates a separate throttled function that's only called once.
2378 * const throttledOperation = throttle({ concurrency: 10, rate: 5 }, operation);
2379 * throttledOperation();
2380 * }
2381 * ```
2382 *
2383 * A better way to use throttle avoids creating a named `operation` function
2384 * altogether, ensuring it cannot be accidentally called without throttling:
2385 *
2386 * ```typescript
2387 * const operation = throttle({ concurrency: 10, rate: 5 }, async () => {
2388 * ...
2389 * });
2390 * ```
2391 *
2392 * Throttle supports functions with arguments automatically infers the correct
2393 * type for the returned function:
2394 *
2395 * ```typescript
2396 * // `operation` inferred to have type (str: string) => Promise<string>
2397 * const operation = throttle({ concurrency: 10, rate: 5 }, async (str: string) => {
2398 * return string;
2399 * });
2400 * ```
2401 *
2402 * In addition to limiting concurrency and invocation rate, `throttle` also
2403 * supports retrying failed invocations, memoizing calls, and on-disk caching.
2404 * See {@link Limits} for details.
2405 *
2406 * @param limits - see {@link Limits}.
2407 * @param fn - The function to throttle. It can take any arguments, but must
2408 * return a Promise (which includes `async` functions).
2409 * @returns Returns a throttled function with the same signature as the argument
2410 * `fn`.
2411 * @public
2412 */
2413export declare function throttle<A extends any[], R>(limits: Limits, fn: (...args: A) => Promise<R>): (...args: A) => Promise<R>;
2414
2415declare type UUID = string;
2416
2417declare class Wrapper {
2418 executing: boolean;
2419 protected verbose: boolean;
2420 protected funcs: ModuleType;
2421 protected child?: childProcess.ChildProcess;
2422 protected childPid?: number;
2423 protected log: (msg: string) => void;
2424 protected queue: AsyncIterableQueue<Message>;
2425 readonly options: Required<WrapperOptions>;
2426 protected monitoringTimer?: NodeJS.Timer;
2427 constructor(fModule: ModuleType, options?: WrapperOptions);
2428 protected lookupFunction(request: object): AnyFunction;
2429 protected stopCpuMonitoring(): void;
2430 protected startCpuMonitoring(pid: number, callId: string): void;
2431 stop(): void;
2432 execute(callingContext: CallingContext, { errorCallback, onMessage, measureCpuUsage }: WrapperExecuteOptions): Promise<void>;
2433 protected logLines: (msg: string) => void;
2434 protected setupChildProcess(): childProcess.ChildProcess;
2435}
2436
2437declare interface WrapperExecuteOptions {
2438 errorCallback?: ErrorCallback;
2439 onMessage: MessageCallback;
2440 measureCpuUsage?: boolean;
2441}
2442
2443declare interface WrapperOptions {
2444 /**
2445 * Logging function for console.log/warn/error output. Only available in
2446 * child process mode. This is mainly useful for debugging the "local"
2447 * mode which runs code locally. In real clouds the logs will end up in the
2448 * cloud logging service (e.g. Cloudwatch Logs, or Google Stackdriver logs).
2449 * Defaults to console.log.
2450 */
2451 wrapperLog?: (msg: string) => void;
2452 childProcess?: boolean;
2453 childProcessMemoryLimitMb?: number;
2454 childProcessTimeoutMs?: number;
2455 childProcessEnvironment?: {
2456 [key: string]: string;
2457 };
2458 childDir?: string;
2459 wrapperVerbose?: boolean;
2460 validateSerialization?: boolean;
2461}
2462
2463export { }
2464
\No newline at end of file