diff --git a/config/redirects b/config/redirects index d437be97..8d889d1a 100644 --- a/config/redirects +++ b/config/redirects @@ -14,7 +14,7 @@ symlink: current -> v2.0 [*-v1.20]: ${prefix}/${version}/aggregation/vector-search -> ${base}/${version}/aggregation/ [*-v1.20]: ${prefix}/${version}/builders -> ${base}/${version}/ -# standardization redirects +[v1.20-*]: ${prefix}/${version}/encryption/ -> ${base}/${version}/ # redirects in standardized docs [v1.20-*]: ${prefix}/${version}/tutorial/install-php-library/ -> ${base}/${version}/get-started/download-and-install/ @@ -54,3 +54,6 @@ symlink: current -> v2.0 [*-v1.19]: ${prefix}/${version}/whats-new/ -> ${base}/${version}/ [*-v1.19]: ${prefix}/${version}/aws-lambda/ -> ${base}/${version}/tutorial/aws-lambda/ +[v1.20-*]: ${prefix}/${version}/indexes/ -> ${base}/${version}/indexes-temp/ +[v1.20-*]: ${prefix}/${version}/read/change-streams/ -> ${base}/${version}/monitoring/change-streams/ +[v1.20-*]: ${prefix}/${version}/tutorial/server-selection/ -> ${base}/${version}/connect/ \ No newline at end of file diff --git a/source/data-formats/codecs.txt b/source/data-formats/codecs.txt deleted file mode 100644 index b817eeb9..00000000 --- a/source/data-formats/codecs.txt +++ /dev/null @@ -1,118 +0,0 @@ -.. _php-codecs: - -====== -Codecs -====== - - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -.. versionadded:: 1.17 - -Overview --------- - -Codecs are used to decode BSON documents into PHP objects, and encode PHP objects into BSON documents. In contrast to -other methods (e.g. type maps), codecs allow for greater customization and handling of different data types. They -separate logic for BSON encoding and decoding from the domain classes, which also enables BSON to be decoded into plain -old PHP objects. - -Handling Documents ------------------- - -The main logic is contained in a document codec. This class implements the ``MongoDB\Codec\DocumentCodec`` interface and -defines what data types can be encoded/decoded and how. The following example defines a ``Person`` class and a codec to -transform it: - -.. literalinclude:: /examples/codecs/handling-documents/Person.php - :language: php - -.. literalinclude:: /examples/codecs/handling-documents/PersonCodec.php - :language: php - -To then use this codec with a collection, specify the ``codec`` option when selecting the collection: - -.. literalinclude:: /examples/codecs/handling-documents/using-codec.php - :language: php - -The example above selects a collection and instructs it to use the ``PersonCodec`` for encoding and decoding documents. -When inserting data, the ``PersonCodec`` is used to encode the document. When retrieving data, the same ``PersonCodec`` -is used to decode BSON data into a ``Person`` instance. Note that while the ``PersonCodec`` could technically decode any -BSON document that contains a name field, we wouldn't want to use it for any other documents. Document codecs are meant -to be used with a :phpclass:`MongoDB\Collection`, or when decoding embedded documents. - -When using a collection with a codec, the codec will only accept and return data of that type for certain operations. -Insert and replace operations (e.g. ``insertOne``, ```findOneAndReplace``, and some ``bulkWrite`` operations) will -attempt to encode the given data using the provided codec. Trying to insert or replace a document that cannot be encoded -will result in an exception. Read operations (e.g. ``aggregate``, ``find``, and ``findOneAndUpdate``) will attempt to -decode returned documents using the provided codec. If the codec does not support the data returned, an exception will -be thrown. - -You can disable codec usage for a specific operation or use a different codec (e.g. to decode the result of an -aggregation pipeline) by specifying ``null`` for the ``codec`` option for any operation. Alternatively, specifying a -type map using the ``typeMap`` operation will also override the collection-level codec: - -.. literalinclude:: /examples/codecs/handling-documents/disabling-codec.php - :language: php - -.. _php-codec-handling-data-types: - -Handling Fields and Data Types ------------------------------- - -The previous example showed how to define a codec for a specific class. However, you may want to create a codec that -handles a particular data type in any document. This can be achieved by implementing the ``MongoDB\Codec\Codec`` -interface. - -The following example defines a codec that stores ``DateTimeInterface`` instances as an embedded document containing a -BSON date and accompanying timezone string. Those same embedded documents can then be translated back into a -``DateTimeImmutable`` during BSON decoding. - -.. literalinclude:: /examples/codecs/handling-data-types/DateTimeCodec.php - :language: php - -.. note:: - When writing a codec, you should be as lenient as possible when it comes to handling data. In this case, the codec - handles any ``DateTimeInterface`` when encoding to BSON, as a ``UTCDateTime`` instance can be created from any such - object. When decoding data from BSON, it will always decode to a ``DateTimeImmutable`` instance. - -This codec can now be leveraged by other codecs that handle date fields. - -First, we add a ``createdAt`` field to the ``Person`` class: - -.. literalinclude:: /examples/codecs/handling-data-types/Person.php - :language: php - -Last but not least, we modify the codec to handle the new field: - -.. literalinclude:: /examples/codecs/handling-data-types/PersonCodec.php - :language: php - -Handling Embedded Documents ---------------------------- - -A previous example showed how to handle a single document. However, sometimes you want to handle fields that contain -embedded documents. We will demonstrate this using an ``Address`` document, which we will embed within a ``Person`` -document. To ensure consistency, we're going to make this a read-only class: - -.. literalinclude:: /examples/codecs/handling-embedded-documents/Address.php - :language: php - -We can now create a document codec for this class: - -.. literalinclude:: /examples/codecs/handling-embedded-documents/AddressCodec.php - :language: php - -The ``Person`` class gets a new ``address`` field, but we'll leave this optional: - -.. literalinclude:: /examples/codecs/handling-embedded-documents/Person.php - :language: php - -The ``PersonCodec`` can now handle the optional ``address`` field when transforming data: - -.. literalinclude:: /examples/codecs/handling-embedded-documents/PersonCodec.php - :language: php diff --git a/source/indexes.txt b/source/indexes-temp.txt similarity index 100% rename from source/indexes.txt rename to source/indexes-temp.txt diff --git a/source/read/change-streams.txt b/source/monitoring/change-streams.txt similarity index 100% rename from source/read/change-streams.txt rename to source/monitoring/change-streams.txt diff --git a/source/tutorial/commands.txt b/source/tutorial/commands.txt index 4305e07a..5351dfe0 100644 --- a/source/tutorial/commands.txt +++ b/source/tutorial/commands.txt @@ -152,3 +152,4 @@ The output would then resemble: float(1) } } +} \ No newline at end of file diff --git a/source/tutorial/encryption.txt b/source/tutorial/encryption.txt deleted file mode 100644 index 70b99df3..00000000 --- a/source/tutorial/encryption.txt +++ /dev/null @@ -1,274 +0,0 @@ -:orphan: - -================= -In-Use Encryption -================= - -.. meta:: - :description: Learn how to implement in-use encryption in PHP projects with the MongoDB PHP Library, including managing encryption keys and configuring client-side field level encryption. - - -.. contents:: On this page - :local: - :backlinks: none - :depth: 3 - :class: singlecol - - -Dependencies ------------- - -To get started using in-use encryption in your project, the -:php:`extension ` will need to be compiled with -`libmongocrypt `_ (enabled by -default). - -Additionally, either ``crypt_shared`` or ``mongocryptd`` are required in order to -use *automatic* client-side encryption. Neither is required for *explicit* -encryption. - -``crypt_shared`` -~~~~~~~~~~~~~~~~ - -The :manual:`Automatic Encryption Shared Library ` -(``crypt_shared``) provides the same functionality as ``mongocryptd``, but does not -require you to spawn another process to perform automatic encryption. - -By default, the extension attempts to load ``crypt_shared`` from the system -path(s) and uses it automatically if found. To load ``crypt_shared`` from -another location, use the ``cryptSharedLibPath`` auto encryption -:php:`driver option ` -when constructing a client. If the extension cannot load ``crypt_shared`` it -will attempt to fallback to using ``mongocryptd`` by default. The -``cryptSharedLibRequired`` option may be used to always require ``crypt_shared`` -and fail if it cannot be loaded. - -For detailed installation instructions see the MongoDB documentation for the -:manual:`Automatic Encryption Shared Library `. - -``mongocryptd`` -~~~~~~~~~~~~~~~ - -The ``mongocryptd`` binary is an alternative requirement for automatic client-side -encryption and is included as a component in the -:manual:`MongoDB Enterprise Server package `. -For detailed installation instructions see the -:manual:`MongoDB documentation on mongocryptd `. - -``mongocryptd`` performs the following: - -- Parses the automatic encryption rules specified in the client configuration. - If the ``schemaMap`` auto encryption driver option contains invalid syntax, - ``mongocryptd`` returns an error. - -- Uses the specified automatic encryption rules to mark fields in read and write - operations for encryption. - -- Rejects read/write operations that may return unexpected or incorrect results - when applied to an encrypted field. For supported and unsupported operations, - see :manual:`Supported Operations for Automatic Encryption `. - -A client configured with auto encryption will automatically spawn the -``mongocryptd`` process from the application's ``PATH``. Applications can control -the spawning behavior via various auto encryption -:php:`driver options `. - -``mongocryptd`` is only responsible for supporting automatic client-side encryption -and does not itself perform any encryption or decryption. - -Managing Encryption Keys ------------------------- - -.. seealso:: :manual:`Encryption Key Management ` in the MongoDB manual - -Creating an Encryption Key -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. note:: - - The following examples use a local master key. While this is suitable for - development, a production application should use a supported cloud provider - (e.g. AWS KMS). The master key is used to encrypt locally stored data keys - and thus it is very important that you keep this key secure. - -To create an encryption key, create a -:php:`MongoDB\Driver\ClientEncryption ` -instance with encryption options and use the -:php:`createDataKey() ` -method. The method will return the key ID which can be used to reference the key -later. You can also pass multiple :ref:`alternate names ` for this key -and reference the key by these names instead of the key ID. - -Creating a new data encryption key would typically be done on initial -deployment, but depending on your use case you may want to use more than one -encryption key (e.g. user-specific encryption keys) or create them dynamically. - -.. literalinclude:: /examples/encryption/create_data_key.php - :language: php - -.. _alt_name: - -Referencing Encryption Keys by an Alternative Name -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To reference keys in your application, you can use the ``keyAltName`` -attribute specified when creating the key. The following example creates an -encryption key with an alternative name, which could be done when deploying the -application. The script then encrypts data by referencing the key by its -alternative name using the ``keyAltName`` option instead of ``keyId``. - -.. note:: - - Prior to adding a new key alternate name, you must create a partial, unique - index on the ``keyAltNames`` field. Client-Side Field Level Encryption - depends on server-enforced uniqueness of key alternate names. - -.. literalinclude:: /examples/encryption/key_alt_name.php - :language: php - - -Client-Side Field Level Encryption ----------------------------------- - -Introduced in MongoDB 4.2, -:manual:`Client-Side Field Level Encryption ` allows an -application to encrypt specific data fields in addition to pre-existing MongoDB -encryption features such as -:manual:`Encryption at Rest ` and -:manual:`TLS/SSL (Transport Encryption) `. - -With field level encryption, applications can encrypt fields in documents prior -to transmitting data over the wire to the server. Client-side field level -encryption supports workloads where applications must guarantee that -unauthorized parties, including server administrators, cannot read the encrypted -data. - - -Automatic Client-Side Field Level Encryption -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. note:: - - Automatic client-side field level encryption requires MongoDB 4.2+ Enterprise - or a MongoDB 4.2+ Atlas cluster. - -Automatic client-side field level encryption is enabled by creating a client and -specifying the ``autoEncryption`` -:php:`driver option `. -The following examples demonstrate how to setup automatic client-side field -level encryption and use a -:php:`MongoDB\Driver\ClientEncryption ` -object to create a new encryption key. - - -.. _server-side: - -Server-Side Field Level Encryption Enforcement -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -The MongoDB 4.2+ server supports using schema validation to enforce encryption -of specific fields in a collection. This schema validation will prevent an -application from inserting unencrypted values for any fields marked with the -:manual:`"encrypt" schema keyword `. - -The following example sets up a collection with automatic encryption using a -``$jsonSchema`` validator and -:manual:`Encryption Schema syntax `. -Data in the ``encryptedField`` field is automatically encrypted on insertion and -decrypted when reading on the client side. - -.. literalinclude:: /examples/encryption/csfle-automatic_encryption-server_side_schema.php - :language: php - - -Providing Local Automatic Encryption Rules -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -The following example uses the ``schemaMap`` auto encryption driver option to -define encrypted fields using a -:manual:`strict subset of the JSON schema syntax `. - -Using ``schemaMap`` in conjunction with a :ref:`server-side schema ` -provides more security than relying entirely on a schema obtained from the -server. It protects against a malicious server advertising a false schema, which -could trick the client into sending unencrypted data that should be encrypted. - -.. note:: - - Only :manual:`Encryption Schema syntax ` - can be used with the ``schemaMap`` option. Do not specify document validation - keywords in the automatic encryption rules. To define document validation - rules, configure :manual:`schema validation `. - -.. literalinclude:: /examples/encryption/csfle-automatic_encryption-local_schema.php - :language: php - - -Explicit Encryption -~~~~~~~~~~~~~~~~~~~ - -Explicit encryption is a MongoDB community feature and does not use -``crypt_shared`` or ``mongocryptd``. Explicit encryption is provided by the -:php:`MongoDB\Driver\ClientEncryption ` class. - -.. literalinclude:: /examples/encryption/csfle-explicit_encryption.php - :language: php - - -Explicit Encryption with Automatic Decryption -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Although automatic encryption requires MongoDB 4.2+ enterprise or a MongoDB 4.2+ -Atlas cluster, automatic *decryption* is supported for all users. To configure -automatic decryption without automatic encryption set the -``bypassAutoEncryption`` auto encryption -:php:`driver option ` -when constructing a client. - -.. literalinclude:: /examples/encryption/csfle-explicit_encryption_automatic_decryption.php - :language: php - - -Queryable Encryption --------------------- - -Introduced in MongoDB 7.0, -:manual:`Queryable Encryption ` is another -form of in-use encryption. Data is encrypted client-side. Queryable Encryption -supports indexed encrypted fields, which are further processed server-side. - - -Automatic Queryable Encryption -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. note:: - - Automatic queryable encryption requires MongoDB 7.0+ Enterprise or a MongoDB - 7.0+ Atlas cluster. - -Automatic encryption in Queryable Encryption utilizes ``crypt_shared`` or -``mongocryptd`` to automatically encrypt and decrypt data client-side. The data -in the ``encryptedIndexed`` and ``encryptedUnindexed`` fields will be -automatically encrypted on insertion and decrypted when querying on the client -side. Additionally, it is possible to query on the ``encryptedIndexed`` field. - -.. literalinclude:: /examples/encryption/queryable_encryption-automatic.php - :language: php - - -Explicit Queryable Encryption -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. note:: - - Explicit queryable encryption requires MongoDB 7.0+. - -Explicit encryption in Queryable Encryption is performed using the -:php:`MongoDB\Driver\ClientEncryption::encrypt() ` -and :php:`decrypt() ` methods. Although -values must be explicitly encrypted (e.g. insertions, query criteria), automatic -*decryption* for queries is possible by configuring ``encryptedFields`` on the -collection, as demonstrated in the following example: - -.. literalinclude:: /examples/encryption/queryable_encryption-explicit.php - :language: php diff --git a/source/tutorial/server-selection.txt b/source/tutorial/server-selection.txt deleted file mode 100644 index 62c20cae..00000000 --- a/source/tutorial/server-selection.txt +++ /dev/null @@ -1,196 +0,0 @@ -:orphan: - -=============================== -Server Selection and Monitoring -=============================== - -.. meta:: - :description: Understand how the MongoDB PHP Library selects and monitors servers, including connection string options for server selection and monitoring. - - -.. contents:: On this page - :local: - :backlinks: none - :depth: 2 - :class: singlecol - -Server Selection and Monitoring -------------------------------- - -Before any operation can be executed, the |php-library| must first select a -server from the topology (e.g. replica set, sharded cluster). Selecting a server -requires an accurate view of the topology, so the extension regularly monitors -the servers to which it is connected. - -In most other drivers, server discovery and monitoring is handled by a -background thread; however, the PHP driver is single-threaded and must therefore -perform monitoring *between* operations initiated by the application. - -Consider the following example application: - -.. code-block:: php - - test; - - /** - * The library creates an internal object for this operation and must select - * a server to use for executing that operation. - * - * If this is the first operation on the underlying libmongoc client, it must - * first discover the topology. It does so by establishing connections to any - * host(s) in the seed list (this may entail TLS and OCSP verification) and - * issuing "hello" commands. - * - * In the case of a replica set, connecting to a single host in the seed list - * should allow the driver to discover all other members in the replica set. - * In the case of a sharded cluster, the driver will start with an initial - * seed list of mongos hosts and, if SRV polling is utilized, may discover - * additional mongos hosts over time. - * - * If the topology was already initialized (i.e. this is not the first - * operation on the client), the driver may still need to perform monitoring - * (i.e. "hello" commands) and refresh its view of the topology. This process - * may entail adding or removing hosts from the topology. - * - * Once the topology has been discovered and any necessary monitoring has - * been performed, the driver may select a server according to the rules - * outlined in the server selection specification (e.g. applying a read - * preference, filtering hosts by latency). - */ - $database->command(['ping' => 1]); - -Although the application consists of only a few lines of PHP, there is actually -quite a lot going on behind the scenes! Interested readers can find this process -discussed in greater detail in the following documents: - -- `Single-threaded Mode `_ in the libmongoc documentation -- `Server Discovery and Monitoring `_ specification -- `Server Selection `_ specification - -Connection String Options -------------------------- - -There are several connection string options relevant to server selection and -monitoring. - -connectTimeoutMS -~~~~~~~~~~~~~~~~ - -``connectTimeoutMS`` specifies the limit for both establishing a connection to -a server *and* the socket timeout for server monitoring (``hello`` commands). -This defaults to 10 seconds for single-threaded drivers such as PHP. - -When a server times out during monitoring, it will not be re-checked until at -least five seconds -(`cooldownMS `_) -have elapsed. This timeout is intended to avoid having single-threaded drivers -block for ``connectTimeoutMS`` on *each* subsequent scan after an error. - -Applications can consider setting this option to slightly more than the greatest -latency among servers in the cluster. For example, if the greatest ``ping`` time -between the PHP application server and a database server is 200ms, it may be -reasonable to specify a timeout of one second. This would allow ample time for -establishing a connection and monitoring an accessible server, while also -significantly reducing the time to detect an inaccessible server. - -heartbeatFrequencyMS -~~~~~~~~~~~~~~~~~~~~ - -``heartbeatFrequencyMS`` determines how often monitoring should occur. This -defaults to 60 seconds for single-threaded drivers and can be set as low as -500ms. - -serverSelectionTimeoutMS -~~~~~~~~~~~~~~~~~~~~~~~~ - -``serverSelectionTimeoutMS`` determines the maximum amount of time to spend in -the server selection loop. This defaults to 30 seconds, but applications will -typically fail sooner if ``serverSelectionTryOnce`` is ``true`` and a smaller -``connectTimeoutMS`` value is in effect. - -The original default was established at a time when replica set elections took -much longer to complete. Applications can consider setting this option to -slightly more than the expected completion time for an election. For example, -:manual:`Replica Set Elections ` states that -elections will not typically exceed 12 seconds, so a 15-second timeout may be -reasonable. Applications connecting to a sharded cluster may consider a smaller -value still, since ``mongos`` insulates the driver from elections. - -That said, ``serverSelectionTimeoutMS`` should generally not be set to a value -smaller than ``connectTimeoutMS``. - -serverSelectionTryOnce -~~~~~~~~~~~~~~~~~~~~~~ - -``serverSelectionTryOnce`` determines whether the driver should give up after -the first failed server selection attempt or continue waiting until -``serverSelectionTimeoutMS`` is reached. PHP defaults to ``true``, which allows -the driver to "fail fast" when a server cannot be selected (e.g. no primary -during a failover). - -The default behavior is generally desirable for a high-traffic web applications, -as it means the worker process will not be blocked in a server selection loop -and can instead return an error response and immediately go on to serve another -request. Additionally, other driver features such as retryable reads and writes -can still enable applications to avoid transient errors such as a failover. - -That said, applications that prioritize resiliency over response time (and -worker pool utilization) may want to specify ``false`` for -``serverSelectionTryOnce``. - -socketCheckIntervalMS -~~~~~~~~~~~~~~~~~~~~~ - -``socketCheckIntervalMS`` determines how often a socket should be checked (using -a ``ping`` command) if it has not been used recently. This defaults to 5 seconds -and is intentionally lower than ``heartbeatFrequencyMS`` to better allow -single-threaded drivers to recover dropped connections. - -socketTimeoutMS -~~~~~~~~~~~~~~~ - -``socketTimeoutMS`` determines the maximum amount of time to spend reading or -writing to a socket. Since server monitoring uses ``connectTimeoutMS`` for its -socket timeouts, ``socketTimeoutMS`` only applies to operations executed by the -application. - -``socketTimeoutMS`` defaults to 5 minutes; however, it's likely that a PHP web -request would be terminated sooner due to -`max_execution_time `_, -which defaults to 30 seconds for web SAPIs. In a CLI environment, where -``max_execution_time`` is unlimited by default, it is more likely that -``socketTimeoutMS`` could be reached. - -.. note:: - - ``socketTimeoutMS`` is not directly related to server selection and - monitoring; however, it is frequently associated with the other options and - therefore bears mentioning. diff --git a/source/upgrade.txt b/source/upgrade.txt index c37fc106..6f1df22f 100644 --- a/source/upgrade.txt +++ b/source/upgrade.txt @@ -13,7 +13,7 @@ Upgrade Library Versions .. facet:: :name: genre :values: reference - + .. meta:: :keywords: compatibility, backwards compatibility :description: Learn how to upgrade the MongoDB PHP Library and PHP extension, ensuring compatibility and addressing breaking changes. @@ -124,4 +124,4 @@ Version 1.19 and Earlier ~~~~~~~~~~~~~~~~~~~~~~~~ For library versions 1.19 and earlier, see the release notes and associated -JIRA tickets for each release on `GitHub `__. +JIRA tickets for each release on `GitHub `__. \ No newline at end of file