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